因此,我正在做的是使用仅使用file_get_contents
的超级简单PHP代理,我获取HTML并将其转换为UTF-8格式的htmlentities。之后,用jQuery进行AJAX调用,我希望将包含标记的整个HTML,<html><head><body>code..</body></head></html>
放入iframe中,然后使用jQuery遍历它来搜索输入。有没有办法做到这一点?如果可以通过其他方式来实现,我只是在做iframe,因为我认为这是最好的选择。由于它是一个完整的HTML文档,其中包含doctype和所有我认为我不能将它附加到div然后遍历它。我的jQuery代码如下:使用jQuery添加从Doctype开始到iframe的完整HTML
$(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个输入计数。因为如果您访问Google并输入网址javascript: alert(document.getElementsByTagName('input').length)
将会提示N个输入,因为有N个输入。我希望用例子提供的一切都更清楚。
我也会尝试这个答案,关于“追加我的iframeCreate”不会将jQuery的insertAfter函数作为append('iframeCreate.insertAfter($('#result')); //创建iframe')?我是否需要创建一个div并将iframe附加到该div,或者通过追加来表达什么意思? – 2013-04-24 18:31:12
噢,你是完全正确的 – 2013-04-26 01:23:06