1

我在周围看到过类似的问题,但他们似乎都没有对我的案子有帮助的答案......

基本上,我想在使用时加载一些 HTML $.ajax()(在不同的域上),并将其解析为自己的 DOM,这样我就可以在我的实际窗口 DOM 中应用属性和操作 HTML。

$.ajax({
    type: 'GET',
    url: 'http://example.com/index.html',
    dataType: 'html',
    crossDomain: true,
    cache: false,
    success: function(data) 
    {
        var src = $('body img', data).first().attr("src");
        //also tried: var src = $('body', $(data)).first().attr("src"); 
        $('#someDiv img').attr("src", src);
    }
});

示例 HTML 文件在哪里:

<html>
<body>
    <img src="someurl"></img>
</body>
</html>

它适用于 Firefox,但不适用于 IE,无论我尝试什么,每当我尝试解析和读取时,它都会返回 null。有什么建议么?

编辑:

我的问题似乎有些模棱两可。问题在于解析,而不是 AJAX。AJAX 正确返回 html 字符串,但 jQuery 无法解析它。

编辑2:

我找到了一个“解决方案”,但它并没有我想要的那么好,它对 HTML 字符串进行切分和排序,并提取数据,而不是将其应用于 DOM。似乎运行有效,因为我可以预测数据的顺序。

归结起来,它是这样的:

var imgsrcs = new Array(5);
var searchItem = '<img src="';
for (var a=0; a<5; a++) {
    var startLoc = data.search(searchItem) + searchItem.length;
    for (var i=0; i<data.length; i++) {
        if (data.charAt(startLoc + i) == '"')
            break;
        imgsrcs[a] += data.charAt(startLoc + i);
    }
    data = data.substring(startLoc + i, data.length);
}
$('.image').each(function(i) {
    $(this).attr("src", imgsrcs[i]);
}); 

相当丑陋,但我解决了我的问题,所以我想我不妨发布它。

4

1 回答 1

2

This is a Same Origin Policy problem.

The crossDomain flag in jquery's ajax function doesn't automatically make cross domain requests work in all browsers (not all browsers support CORS). Since you're requesting this from a different domain, a normal request won't actually be able to read the data (or even make the request).

Normally, for json data, you can do JSONP, which is what the crossDomain often flag enables. However, JSON is unique because it can be natively read in javascript. Since HTML cannot be read, you'd need to wrap it in parseable javascript to employ a trick like JSONP.

Rather than do that on your own, though, I'd highly suggest that you look into the easyXDM library in order to do cross domain messages like this. You'd essentially open up a hidden iframe on the other domain, and pass messages back and forth between the parent and the hidden frame. And, since the hidden frame is on the same domain as the html, it will have no problem ajaxing for it.

http://easyxdm.net/wp/

于 2012-04-27T06:32:42.960 回答