在一个应用程序中,我想使用 jQuery deferred 在一个中心位置实现我们的 Ajax 成功和错误处理。如果我将字符串放入 data 选项中,一切都很好,但是如果我想在 data 选项中放入一个数组,它会将其作为字符串发送!
我的延迟实施:
Application = {
ajax: function(options) {
var deferred = $.Deferred(function (d) {
var defaults = {
cache: false,
type: 'post',
traditional: true,
dataType: 'json'
},
settings = $.extend({}, defaults, options);
d.done(settings.success);
d.fail(settings.error);
d.done(settings.complete);
var jqXHRSettings = $.extend({}, settings, {
success: function (response, textStatus, jqXHR) {
/*
JSON Reponse
{
status: 'error' or 'success',
code: 200, (HTTP codes or own codes between 600 and 700 for business logic errors)
data: { <result> }
}
*/
if (settings.dataType === 'json') {
if (response.status == 'success') {
// Just resolve and give data back
d.resolve(response.data);
} else if (response.status == 'error') {
// Implement error handling
d.reject(response.data);
}
} else {
d.resolve(response);
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
d.reject(jqXHR);
},
complete: d.resolve
});
$.ajax(jqXHRSettings);
});
var promise = deferred.promise();
promise.success = deferred.done;
promise.error = deferred.fail;
promise.complete = deferred.done;
return promise;
}
};
我对这个延迟函数的实现(不起作用!):
// Retrieve all sessions from fullcalendars
var ajax = Application.ajax({
url: Routing.generate($this.options.ajaxScheduleSessionsRoute, { _format: 'json', id: this.options.scheduleId }),
data: {
"rooms": $this._rooms // $this._rooms is an array! [1, 2, 3, 4, 5]
}
});
ajax.fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
});
ajax.done(function(response, textStatus, jqXHR){
console.log(response);
});
结果(缺少 [])
使用上述延迟函数之前的 jQuery ajax 的默认实现(这有效!):
$.ajax({
type: 'POST',
url: Routing.generate($this.options.ajaxScheduleSessionsRoute, { _format: 'json', id: this.options.scheduleId }),
data: {
"rooms": $this._rooms
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText);
},
success: function(data) {
$.each(data, function( key, source ) {
var roomId = key;
console.log(source);
$('#calendar'+key).fullCalendar( 'addEventSource', source );
});
},
dataType: 'json'
});
结果(带有 [])
问题: 为什么使用 jQuery Ajax 的默认实现可以工作,而延迟函数却不行?