我想在执行请求之前将data
加载到$.ajax
。
我发现了回调:beforeSend: function() {}
但是,如果不幸的是,如果知道如何更改data
方法的$.ajax
参数。
请帮忙。
这是我的方法:
$.ajax('@myInsurance.controllers.routes.Insurances.submit()', {
data: null,
beforeSend : function(){
setData();
},
contentType: 'application/json',
type: "POST",
dataType: 'json',
error: function(response, status, xhr) {
showNotyfication(status, response.responseText);
},
success: function(response, status, xhr) {
showNotyfication('success',response)
},
});
function setData() {
var vdata;
vdata.value = otherAjaxAsyncCall()};
vdata.version = 1;
return vdata;
}
答案 0 :(得分:1)
此设置无效。您的其他AJAX调用是异步的。意味着setData()
函数不会返回正确的值,因为它不会等待另一个AJAX调用完成。
您需要做的是在第一个AJAX调用的success
处理程序中调用第二个AJAX调用:
// first AJAX call
$.ajax('...', {
success: function(response) {
// second AJAX call
$.ajax('...', {
data: {
version: 1,
value: response.value
},
success: function(response) {
// second AJAX request done
console.log(response);
}
})
}
});
答案 1 :(得分:0)
您始终可以在this.data
方法中使用beforeSend
。它指的是ajax对象。
设置必要的数据只需使用
var newData = 'someData';
this.data = newData;
以上将为ajax对象设置必要的数据。实际上,您可以使用this命令访问任何参数。只需在beforeSend
方法中使用调试点,然后在开发人员控制台中键入this
即可查看可用参数。
答案 2 :(得分:0)
您可以从setData
方法返回一个对象,但需要一个承诺,您可以这样使用$.when().then()
:
function setData() {
return $.when(otherAjaxAsyncCall).then(function(data){
var vdata = {}; // <----should be an object
vdata.value = data;
vdata.version = 1;
return vdata;
});
}
现在在ajax中你可以直接使用它:
var data2send = setData(); // call it before this ajax call.
$.ajax({
url: '@myInsurance.controllers.routes.Insurances.submit()',
data: data2send, // <-- set it here as you are returning from "setData"
beforeSend : function(){},
contentType: 'application/json',
type: "POST",
dataType: 'json',
error: function(response, status, xhr) {
showNotyfication(status, response.responseText);
},
success: function(response, status, xhr) {
showNotyfication('success',response)
}
});