[英]jQuery AJAX Call Triggers Error Function
我在代碼中使用了這個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.
XMLHttpRequest cannot load https://s3.amazonaws.com/GSTArticles/GoogleMaps/Landmarks.xml. Origin null is not allowed by Access-Control-Allow-Origin.
您需要使用jsonp來使用ajax進行跨域請求-這意味着您無法使用jQuery的ajax方法來請求XML。 這是其他相關問題。
您可以使用Yahoo API庫(YQL)來獲取xml
// 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.