1

我在我的代码中使用这个 ajax 调用,但它每次都会触发错误函数。有人知道为什么会这样吗?

$.ajax({
    type:'GET',
    url: 'https://s3.amazonaws.com/GSTArticles/GoogleMaps/Landmarks.xml',
    datatype: 'xml',
    success: function(xml){
        console.log(xml);
    },
    error: function(err){
        alert("ERROR!");
    }
});

据我了解,语法看起来是正确的。有人可以帮我看看为什么这会触发错误,而不是将 xml 放入我的控制台吗?谢谢。

我也在控制台中看到了这一点:XMLHttpRequest cannot load https://s3.amazonaws.com/GSTArticles/GoogleMaps/Landmarks.xml. Origin null is not allowed by Access-Control-Allow-Origin.

4

1 回答 1

1

您需要使用 jsonp 通过 ajax 进行跨域请求 - 这意味着您不能使用 jQuery 的 ajax 方法请求 XML。以下是其他相关问题。

Jquery的跨域问题

如何在 jQuery 中解析 XML 跨域?

您可以使用Yahoo API 库 (YQL)来获取 xml

来源http://www.cypressnorth.com/blog/programming/cross-domain-ajax-request-with-xml-response-for-iefirefoxchrome-safari-jquery/

// Accepts a url and a callback function to run.
function requestCrossDomain(site, callback) {

    // If no url was passed, exit.
    if (!site) {
        alert('No site was passed.');
        return false;
    } 
    // Take the provided url, and add it to a YQL query. Make sure you encode it!
    var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';

    // Request that YSQL string, and run a callback function.
    // Pass a defined function to prevent cache-busting.
    $.getJSON(yql, cbFunc);

    function cbFunc(data) {
        // If we have something to work with...
        if (data.results[0]) {
            if (typeof callback === 'function') {
                callback(data);
            }
        }
        // Else, Maybe we requested a site that doesn't exist, and nothing returned.
        else throw new Error('Nothing returned from getJSON.');
    }
}
function xmlSuccess(data){
    console.log(data.results[0]);
}
requestCrossDomain('https://s3.amazonaws.com/GSTArticles/GoogleMaps/Landmarks.xml',xmlSuccess);

小提琴

于 2013-06-18T18:42:22.390 回答