[英]How to get the response text from an AJAX request using jQuery
我正在嘗試向服務器發出JSONP請求。 這是我的代碼:
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function() {
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});//code indentation
當我運行代碼時會出錯。 但是,如果我在Chrome(ctrl + shift + I)中打開開發人員工具,則可以在“網絡”下看到請求。 單擊它顯示正確的響應(並顯示請求已被接受)。
道歉是一個非常明顯的解決方案(我曾嘗試過搜索,但是沒有運氣),但在這一點上,我感到非常困惑。 任何幫助將非常感激。
::編輯::
將錯誤函數更改為:
error: function() {
console.log('error', arguments);
},
由於下面的Aaron Digulla,返回了消息“未調用jsonCallback”。
來自服務器的響應是JSON,而不是JSONP(已通過JSONlint檢查)
當您說“它出錯”時,我的猜測是您得到alert(2)
。 要找出原因,請將函數參數記錄到控制台:
...
error: function() {
console.log('error', arguments);
},
...
jQuery會將其他信息(例如錯誤消息)傳遞給該函數。 那應該可以幫助您了解其失敗的原因。
例如,對於success
功能,獲取服務器響應的情況同樣如此。
[編輯]
我收到
jsonCallback was not called
的錯誤
這意味着您的服務器沒有返回JSONP。 JSONP看起來像name({...})
而普通的JSON看起來像{...}
。 請檢查您服務器的配置,並確保它實際上支持JSONP,並且響應看起來正確。
我應該已經從您的代碼中看到了這一點:
dataType: 'jsonp'
headers: {
'Accept': 'application/json', //this is required by the server
}
這意味着您正在發送無效的JSONP / JSON組合。 如果您使用特定的dataType
,那么讓jQuery構建正確的標頭。
成功函數具有參數,您可以從該參數獲取響應文本。
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function(response) {
alert(response);
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});
您無法為jsonp請求設置async: false
,因為其性質如此,因此添加了腳本標記以處理響應方法。
dataType: 'jsonp
如您所述,您希望從服務器返回的數據類型為jsonp,但可能是您的服務器將返回任何其他格式,而不是jsonp ..因此,請在瀏覽器的“網絡”下檢查服務器返回的響應類型控制台...如果不是jsonp格式,請更改您的響應返回類型...。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.