javascript - jQuery:遍历 Chrome/Safari 中的 AJAX 响应

标签 javascript ajax jquery google-chrome

我正在尝试遍历包含远程网页(HTML 输出)的 AJAX 响应。

我的目标是遍历远程页面的“脚本”、“链接”和“标题”元素 - 必要时加载它们,并将其内容嵌入到当前页面。

它在 FF/IE 中运行良好,但出于某种原因 - Chrome 和 Safari 的行为不同: 当我对响应运行 .each() 循环时,Chrome/Safari 似乎忽略了页面部分下的所有内容。

这是我当前的代码:

$.ajax({
    url: 'remoteFile.php',
    cache: false,
    dataFilter: function(data) { 
        console.log(data); 
        /* The output seems to contain the entire response, including the <head> section - on all browsers, including Chrome/Safari */

        $(data).filter("link, script, title").each(function(i) {
            console.log($(this)); 
            /* IE/FF outputs all of the link/script/title elements, Chrome will output only those that are not in the <head> section */
        });

        console.log($(data)); 
        /* This also outputs the incomplete structure on Chrome/Safari */

        return data;
    },
    success: function(response) {}
});

我已经为这个问题苦苦挣扎了一段时间,我在谷歌搜索中发现了一些其他类似的案例,但没有真正的解决方案。 这发生在 jQuery 1.4.2 和 jQuery 1.3.2 上。

我真的不想用 .indexOf() 和 .substring() 来解析响应——在我看来,这对客户端来说太过分了。

非常感谢!

最佳答案

我认为这与 jQuery 如何处理 HTML 字符串并从中创建 DOM 节点有关。在一堆其他事情中,jQuery 将创建一个临时的 <div>并设置它的 innerHTML传递给 $(...) 的任何 HTML从而生成一堆 DOM 节点,可以从 <div> 中提取这些节点并作为 jQuery 集合返回给您。

这个问题,我相信,是因为 <html> 引起的, <head><body>元素,所有这些都不能很好地附加到 <div>元素。浏览器的行为往往不同,有些浏览器似乎忽略了这些顶级元素,只是将它们的内容交还给您——其他浏览器则完全忽略这些元素,甚至不会给您它们的后代。

看来,避免这种跨浏览器问题的方法是在解析之前简单地将麻烦的元素替换为其他一些假元素。例如

$(
    // replace <html> with <foohtml> .. etc.
    data.replace(/<(\/?)(head|html|body)(?=\s|>)/g, '<foo$1$2')
).filter("link, script, title").each(function(i) {
    console.log($(this));
    // do your stuff
});

另外,我不认为filter就足够了,因为它不会针对后代元素。这可能是更好的方法:

$(
    // replace <html> with <foohtml> .. etc.
    data.replace(/<(\/?)(head|html|body)(?=\s|>)/g, '<foo$1$2')
).find('link,script,title').andSelf().filter("link,script,title").each(function(i) {
    console.log($(this));
    // do your stuff
});

关于javascript - jQuery:遍历 Chrome/Safari 中的 AJAX 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3052503/

相关文章:

php - AJAX 定期检查

javascript - 下载 JPG、PNG 格式时,签名板上的 Canvas 签名变成全黑

jquery - 为什么是:last-child not giving me the results I expect?

javascript - 用于响应式网页设计的 jQuery

javascript - 使用 getImageData 进行 JS Canvas 碰撞检测

javascript - PHP&JS加密/签名和验证二维码

javascript - jQuery:单击 native 音频元素

javascript - 从 Javascript 调用方法

asp.net - Ajax.ActionLink无法正常工作,Response.IsAjaxRequest()始终为false

javascript - 类型错误 : a is null