从deferred.then()返回数据时保留参数

时间:2015-05-24 13:13:32

标签: javascript jquery promise

如何在deferred.then回调中返回数据时传递多个参数?

var data = {
    json: JSON.stringify({
        text: 'some text',
        array: [1, 2, 'three'],
        object: {
            par1: 'another text',
            par2: [3, 2, 'one'],
            par3: {}
        }
    }),
    delay: 3
};

$.ajax({
    url:'/echo/json/',
    data: data,
    type: 'POST'
}).then(function(response, statusText, jqXhr){
    response.text = 'foo';
    // how to return the rest of the arguments correctly?
    return response;
}).done(function(response, statusText, jqXhr){
    console.log(response); // <- altered response
    console.log(statusText); // <- how to pass it along?
    console.log(jqXhr); // <- how to pass it along?
});

http://jsfiddle.net/rv1aydvb/

2 个答案:

答案 0 :(得分:2)

您需要使用deferred返回使用多个值解析的resolveWith method。当然,返回单个(但复合)值通常更清晰。

$.ajax(…).then(function(response) {
    response.text = 'foo';
    return $.Deferred().resolveWith(this, arguments); // if you don't replace but modify vals
    // alternatively,  .resolveWith(this, [response, …]);
}).done(function(response, statusText, jqXhr) {…});

答案 1 :(得分:0)

返回一个带有statusText和jqXhr的对象。然后,您可以将其作为响应对象的一部分进行访问。像这样

$.ajax({
    url:'/echo/json/',
    data: data,
    type: 'POST'
}).then(function(response, statusText, jqXhr){
    response.text = 'foo';
    return {
        response: response,
        status: statusText,
        jq: jqXhr
    }
}).done(function(response, statusText, jqXhr){
    console.log(response); // <- altered response
    console.log(response.status); // <- undefined
    console.log(response.jq); // <- undefined

});

https://jsfiddle.net/rv1aydvb/3/