![](/img/trans.png)
[英]How to get the ajax response from success and assign it in a variable using jQuery?
[英]How to get response text from ajax callback in a variable using ExtJS
我想知道是否可以從Ext.Ajax.Request
調用中獲取變量中的responseText
。 我嘗試了許多方法,並且“破解”都沒有成功。
在這種情況下,我試圖將responseText
分配給accStatus
變量,並且我總是變得undefined
(我知道這不是正確的方法),但是我想確切地知道如何處理 (正確的方法)並將其return
我的function
沒有問題,並且使用“簡單”的方式(如果可能),如下面的代碼所示。
順便說一句,我正在使用Ext 4.2.0 。
Ext.define('Util.AccountManager', {
singleton: true,
getAccountStatus: function(id) {
var accStatus;
Ext.Ajax.request({
url : 'rest/accounts',
method : 'POST',
params : {id: id},
callback: function(o, s, r) {
accStatus = r.responseText;
}
});
return accStatus;
}
});
Ext.onReady(function () {
var id = '1234';
var accStatus = Util.AccountManager.getAccountStatus(id);
if(accStatus) {
console.log(accStatus);
}
});
如果有人想提供幫助,則可以使用以下URLs
導入ExtJS
:
我也將此jsfiddle
僅僅用於“測試”(或至少嘗試是因為無法通過該站點發出ajax
請求)。
您的getAccountStatus
需要回調,因此您可以在XHR完成后做出響應。 AJAX是異步的,因此您不能期望在對getAccountStatus
的調用返回之前調用成功回調。
// Will never work unless you use synchronous AJAX (which you shouldn't
// because it would block the UI while the request is pending)
var accStatus = Util.AccountManager.getAccountStatus(id);
改為執行以下操作
Ext.define('Util.AccountManager', {
singleton: true,
getAccountStatus: function(id, cb) {
Ext.Ajax.request({
url : 'rest/accounts',
method : 'POST',
// async: true, // This would make your return work, but don't do it
params : {id: id},
callback: function(o, s, r) {
cb(r.responseText);
}
});
// Code here runs before the callback above
}
});
Ext.onReady(function () {
var id = '1234';
var accStatus = Util.AccountManager.getAccountStatus(id, function(status){
console.log(status);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.