所以我正在做的是,使用一个仅使用 file_get_contents
的 super 简单的 PHP 代理我获取 HTML 并将其转换为 UTF-8 格式的 htmlentities。之后,使用正在执行 AJAX 调用的 jQuery,我想获得包含标签 <html><head><body>code..</body></head></html>
的整个 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*/
});
问题是什么都没有加载到 iframe 中,没有抛出错误并且请求成功将 HTML 包含在响应中。例如,如果我给出 URL http://google.com对于脚本,它应该返回 N 个输入的计数。因为如果你去谷歌并输入 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();
关于php - 使用 jQuery 添加从 Doctype 到 iframe 的完整 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16198869/