我正在通過身份驗證進行異步跨域調用。重構使用promise對象的jquery ajax調用
當我驗證我用一個通用的get方法檢索實際應用數據:
define(['jquery'], function ($) {
return {
get: function (url, data) {
// Call to authenticate before retrieve data
$.ajax({
type: 'POST',
url: 'root/authentication',
data: { user: root: password: root },
dataType: 'json',
xhrFields: {
withCredentials: true
},
complete: function (response) {
// Call to retrieve application data
$.ajax({
beforeSend: function (xhr) {
xhr.withCredentials = true;
},
type: 'GET',
url: root + url,
xhrFields: {
withCredentials: true
},
async: true,
dataType: 'json',
crossDomain: true
});
}
});
}
};
});
的上述數據呼叫是通過另一種非通用代碼調用:
define(['cors'],
function(cors) {
return function CustomerService() {
function getCustomers() {
return cors.get('/customers');
}
return {
getCustomers: getCustomers
};
};
})
在我的knockoutjs viewmodel我想這樣做:
當asyc調用執行renderCustomers函數和更新UI。
$.when(customerService.getCustomers())
.done(renderCustomers)
.fail();
function renderCustomers(customers) {
// Add data to knockout observables
}
我需要改變什麼才能讓客戶進入renderCustomers功能?
現在的客戶是未定義的,我想這是因爲我的ajax調用沒有正確設置承諾。
你'GET'函數應該返回'$ .ajax'在'return $ .ajax({...})'中。 – Twisted1919
這是行不通的,因爲他嵌套了ajax調用。 –