Sam*_*pez 1 html php iframe jquery
所以我正在做的是,使用一个超级简单的PHP代理,只使用file_get_contents我获取HTML并将其转换为UTF-8格式的htmlentities.之后使用jQuery进行AJAX调用我希望将包含标签的整个HTML <html><head><body>code..</body></head></html>放到iframe中,然后我可以使用jQuery遍历它来搜索输入.有没有办法做到这一点?如果它可以通过其他受欢迎的方式完成,我只是在做iframe,因为我认为这是最好的选择.因为它是一个带有doctype的完整HTML文档,所以我认为我不能将它附加到div然后遍历它.我的jQuery代码如下:
$(document).ready(function(){
var globalCount = 0;
function countInputs(data, url){
var unparsedHTML = data.html; // get data from json object which is in htmlentities
var iframeCreate = $('<iframe id="iframe"></iframe>');
var iframe = $('#iframe');
if(iframe.length){
iframe.remove(); // if iframe exists remove it to clean it
iframeCreate.insertAfter($('#result')); //create iframe
}else{
iframeCreate.insertAfter($('#result')); //create iframe
}
iframe.html(unparsedHTML).text(); // insert html in iframe using html(text).text() to decode htmlentities as seen in some stackoverflow examples
var inputs = iframe.contents().find('input'); //find inputs on iframe
var count = inputs.length;
var output = '';
globalCount = globalCount + count;
output = "Count for url: " + url + " is: " + count + " , the global count is: " + globalCount;
console.log(output);
$('#result').append(output);
}
/*SNIP ----- SNIP */
function getPage(urls){
console.log("getPage");
for(i = 0; i < urls.length; i++){
var u = urls[i];
console.log("new request: " + urls[i]);
var xhr = $.ajax(
{
url: "xDomain.php",
type: "GET",
dataType: "json",
data: {
"url":u
}
})
xhr.done(function(data){
console.log("Done, starting next function");
countInputs(data, u)
});
xhr.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof console == 'object' && typeof console.log == 'function') {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}
}
/*SNIP------------SNIP*/
});
Run Code Online (Sandbox Code Playgroud)
问题是,没有任何内容被加载到iframe中,不会抛出任何错误,并且请求成功将HTML带入响应中.例如,如果我将URL http://google.com提供给脚本,则应该返回N个输入的计数.因为如果你去谷歌并输入URL javascript: alert(document.getElementsByTagName('input').length)将提醒N个输入,因为有N个输入.我希望通过这个例子,一切都更加清晰.
您需要使用contentDocumentiframe 的属性将内容放入其中.
另外:您需要将iframeCreate附加到文档的某处,否则"#iframe"不会返回任何内容.
http://www.w3schools.com/jsref/prop_frame_contentdocument.asp
这个答案让您知道将所有内容放入iframe的contentDocument中
例:
var iframe = $('#iframe');
var idoc = iframe[0].contentDocument;
idoc.open();
idoc.write(mytext);
idoc.close();
Run Code Online (Sandbox Code Playgroud)