Javascript 从deferred.then()返回数据时保留参数
在回调中返回数据时,如何传递多个参数Javascript 从deferred.then()返回数据时保留参数,javascript,jquery,promise,Javascript,Jquery,Promise,在回调中返回数据时,如何传递多个参数 var data = { json: JSON.stringify({ text: 'some text', array: [1, 2, 'three'], object: { par1: 'another text', par2: [3, 2, 'one'], par3: {} } }), dela
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?
});
var数据={
json:json.stringify({
文本:“一些文本”,
数组:[1,2,'3'],
对象:{
par1:‘另一个文本’,
par2:[3,2,'一'],
par3:{}
}
}),
延误:3
};
$.ajax({
url:“/echo/json/”,
数据:数据,
类型:“POST”
}).then(函数(响应、状态文本、jqXhr){
response.text='foo';
//如何正确返回其余参数?
返回响应;
}).done(函数(响应、状态文本、jqXhr){
console.log(response);//返回一个包含statusText和jqXhr的对象。然后您可以将它们作为response对象的一部分进行访问。如下所示
$.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
});
$.ajax({
url:“/echo/json/”,
数据:数据,
类型:“POST”
}).then(函数(响应、状态文本、jqXhr){
response.text='foo';
返回{
答复:答复,,
状态:statusText,
jq:jqXhr
}
}).done(函数(响应、状态文本、jqXhr){
console.log(response);//您将需要返回使用多个值解析的值。当然,返回单个(但复合)值通常更干净
$.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) {…});
与其返回修改后的数据,不如直接调用下一个函数,并使用修改后的参数。@Barmar返回一个对象时,仍会使参数2和参数3在完成回调中未定义,对吗?我想知道是否有办法在然后回调中设置它们。我知道这是可能的。我问是否有可以定义除第一个参数之外的任何参数。您可以返回一个数组,而不仅仅是一个对象。尽管如此,它最终还是会成为第一个参数是的,但是.done
没有statusText
或jqXhr
。它们是在中处理的ajax调用的一部分。那么您需要什么具体原因吗把它们作为单独的论据?谢谢,我同意这看起来有点混乱。我只是出于好奇才问的