2016-08-15 99 views
0

當我執行一個Ajax調用,我得到以下錯誤:響應Ajax的呼叫不工作

「未捕獲的SyntaxError:意外的標記:」

我的jQuery代碼看起來是這樣的:

$.ajax({ 
    type: 'GET', 
    url: "http://www.exampleUrl.com", 
    crossDomain: true, 
    dataType: "jsonp", 
    jsonp: "jsonp", 
    mimeType: "application/json", 
    jsonpCallback: 'callback', 
    contentType: "application/json; charset=utf-8", 

    beforeSend: function() { 

    }, 
    success: function (data) 
    {   
     alert("success"); 
    }, 
    error: function (result) { 

    } 
}); 

爲什麼我沒有得到json響應。當直接在瀏覽器中使用相同的url時,我得到期待的json響應。 有什麼不對?

回答

1

您肯定遇到了CORS問題。

這種方法應該很好地工作:

$.ajax({ 

    // The 'type' property sets the HTTP method. 
    // A value of 'PUT' or 'DELETE' will trigger a preflight request. 
    type: 'GET', 

    // The URL to make the request to. 
    url: 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html', 

    // The 'contentType' property sets the 'Content-Type' header. 
    // The JQuery default for this property is 
    // 'application/x-www-form-urlencoded; charset=UTF-8', which does not trigger 
    // a preflight. If you set this value to anything other than 
    // application/x-www-form-urlencoded, multipart/form-data, or text/plain, 
    // you will trigger a preflight request. 
    contentType: 'text/plain', 

    xhrFields: { 
    // The 'xhrFields' property sets additional fields on the XMLHttpRequest. 
    // This can be used to set the 'withCredentials' property. 
    // Set the value to 'true' if you'd like to pass cookies to the server. 
    // If this is enabled, your server must respond with the header 
    // 'Access-Control-Allow-Credentials: true'. 
    withCredentials: false 
    }, 

    headers: { 
    // Set any custom headers here. 
    // If you set any non-simple headers, your server must include these 
    // headers in the 'Access-Control-Allow-Headers' response header. 
    }, 

    success: function() { 
    // Here's where you handle a successful response. 
    }, 

    error: function() { 
    // Here's where you handle an error response. 
    // Note that if the error was due to a CORS issue, 
    // this function will still fire, but there won't be any additional 
    // information about the error. 
    } 
}); 

來源:Using CORS

+0

感謝您爲您的文章。現在我得到以下響應錯誤:請求的資源上沒有「Access-Control-Allow-Origin」頭。因此不允許原產地'null'訪問。 –

+0

這表明CORS沒有正確定義或在您使用的服務器上啓用。查看[enable-CORS](http://enable-cors.org/server.html)獲取更多關於如何有效解決問題的信息。 希望你有機會訪問服務器! – nyedidikeke