延迟jQuery AJAX请求不运行done()回调函数

时间:2022-08-23 11:34:03

I have setup a simple demo using jQuery Deferred object with AJAX request to simulate how my app is doing it.

我已经使用带有AJAX请求的jQuery Deferred对象设置了一个简单的演示来模拟我的应用程序是如何做到的。

My issue is, ever since I switched over from the older non-deferred method, I cannot get a success callback.

我的问题是,自从我从旧的非延迟方法切换后,我无法获得成功的回调。

Only the fail() callback is called. Can someone help me to get a successful callback? I don't see where it is going wrong? Appreciate any help

仅调用fail()回调。有人可以帮助我获得成功的回调吗?我不知道哪里出错了?感谢任何帮助

My demo is here http://jsfiddle.net/jasondavis/y645yp4g/4/

我的演示在这里http://jsfiddle.net/jasondavis/y645yp4g/4/

My old AJAX call was like this...

我的旧AJAX电话是这样的......

var ajax = $.ajax({
    type: 'POST',
    async: false,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    url: '/gettask',
    data: {
        action: 'load-task-record',
        task_id: taskId
    },
    success: function(data) {
        // my success functionality here
    }
});

New AJAX call using Deferred object...

使用Deferred对象的新AJAX调用...

// Call function that execute AJAX request and returns it
var ajaxRequest = ajaxLoadTaskData();

ajaxRequest.done(function(response) {

    if( response.success ) {
        alert('AJAX request success');
    }else{
        // output the contents of response.errors
    }

}).fail(function(response) {
    // AJAX request failed
    console.log('response', response);
    alert('AJAX request failed');

}).always(function(response) {

});


// Run AJAX request and return Promise()
function ajaxLoadTaskData() {
    return $.ajax({
        type: 'POST',
        async: false,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        url: '/gettask',
        data: {
            action: 'load-task-record',
            task_id: '1',
        },
    });
}

Mock AJAX response for AJAX request to /gettask

对AJAX请求的模拟AJAX响应/ gettask

// Mock AJAX response for AJAX request to /gettask
$.mockjax({
    url: '/gettask',
    contentType: 'text/json',
    responseTime: 100,
    response: function(settings) {
        console.log('mockJax GET to /gettask :');
        //console.log(settings);
        if (settings.data.value == 'err') {
            this.status = 500;
            this.responseText = 'Validation error!';
        } else {
            var taskrecord = { 'name1': 'bar' };
            this.responseText = taskrecord;
        }
    },
});

1 个解决方案

#1


/gettask doesn't exists in that jsFiddle environment. Use console.log(settings) to see the entire content of the response. You will se that the status is 404.

/ gettask在jsFiddle环境中不存在。使用console.log(设置)查看响应的完整内容。您将看到状态为404。

#1


/gettask doesn't exists in that jsFiddle environment. Use console.log(settings) to see the entire content of the response. You will se that the status is 404.

/ gettask在jsFiddle环境中不存在。使用console.log(设置)查看响应的完整内容。您将看到状态为404。