所以我要做的是,使用一个只使用file_get_contents
的超简单PHP代理,获取一个HTML并将其转换为UTF-8格式的htmlenties。在完成AJAX调用的jQuery之后,我想将包含标记的整个HTML<html><head><body>code..</body></head></html>
放到iframe中,这样我就可以用jQuery遍历它来搜索输入。有办法吗?如果它可以做一些其他的方式也受欢迎,我只是做iframe,因为我认为这是最好的选择。因为它是一个完整的HTML文档,包含doctype和我认为的所有东西,所以我不能将它附加到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*/
});
问题是没有任何东西加载到iframe中,没有抛出错误,请求成功地将HTML引入响应。例如,如果我将URLhttp://google.com赋给脚本,它应该返回N个输入的计数。因为如果你进入Google并输入URL
javascript: alert(document.getElementsByTagName('input').length)
将警告N个输入,因为有N个输入。我希望通过这个例子,一切都会更清楚。 最佳答案
您需要使用iframe的contentDocument
属性来放入内容。
另外:您需要将iframeCreate附加到文档的某个位置,否则“#iframe”不会返回任何内容。
http://www.w3schools.com/jsref/prop_frame_contentdocument.asp
This answer让您了解如何将所有内容放入iframe的contentDocument
例子:
var iframe = $('#iframe');
var idoc = iframe[0].contentDocument;
idoc.open();
idoc.write(mytext);
idoc.close();