今天在项目中请求后台数据的时候,需要先ajax请求数据,获取到其中的一个参数数据,再发出请求。而ajax异步的特性,按正常嵌套并不能得到想要的数据结果。经过查资料和思考,原来是因为async这个属性在嵌套的时候需要设置为false才可以。
$.ajax({
url : "getEsComOrderById",
type : "POST",
dataType : 'json',
async:false,
data : { fid : orderId},
success : function(data) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf"]').attr('content')
},
type: "post",
url: "getEsComOrderById",
async:false,
data: $('.form').serialize(),
dataType: "json",
success: function( res ) {
result = res;
}
});
});
插播另一个小技巧我们ajax请求一次可能会用于多个页面,那么封装成函数会更好些。举个栗子:
function send() {
var result ;
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf"]').attr('content')
},
type: "post",
url: "getEsComOrderById",
async:false,
data: $('.form').serialize(),
dataType: "json",
success: function( res ) {
result = res;
}
});
return result;
}
var res = send();
if (res.code == 0){
$('.brand').html(res.value+'元');
}