$('#submit_id').click(function(){
function mark() {
$.ajax({
type: "POST",
url: "request1.php",
data: $('#form_id').serialize(),
cache: false,
success: function(data1){
}
});
}
function other() {
$.ajax({
type: "POST",
url: "request2.php",
data: $('#form_id').serialize(),
cache: false,
success: function(data2){
}
});
}
$.when(mark(), other()).done(function(data1, data2)
{
console.log(data1);
$(".results1").html(data1);
console.log(data2); // Result
$(".results2").html(data2);
});
});
我需要将返回的数据传递到一个变量中,例如:
控制台:未定义
你必须从你的函数返回 promise 接口,如下所示:
function mark() {
return $.ajax({
type: "POST",
url: "request1.php",
data: $('#form_id').serialize(),
cache: false
});
}
而且您不需要在此处指定成功回调(但您仍然可以(。
你的代码应该像这样工作:
$.when(mark(), other()).done(function(data1, data2){
console.log(data1);
$(".results1").html(data1);
console.log(data2); // Result
$(".results2").html(data2);
});
function mark() {
return $.ajax({
type: "POST",
url: "request1.php",
data: $('#form_id').serialize(),
cache: false
});
}
function other() {
return $.ajax({
type: "POST",
url: "request2.php",
data: $('#form_id').serialize(),
cache: false
});
}
试试这个
$('#submit_id').click(function(){
function mark() {
var res = null;
$.ajax({
type: "POST",
url: "request1.php",
data: $('#form_id').serialize(),
cache: false,
success: function(data1){
res= data1;
}
});
return res;
}
function other() {
var res = null;
$.ajax({
type: "POST",
url: "request2.php",
data: $('#form_id').serialize(),
cache: false,
success: function(data2){
res= data2;
}
});
return res;
}
$.when(mark(), other()).done(function(data1, data2)
{
console.log(data1);
$(".results1").html(data1);
console.log(data2); // Result
$(".results2").html(data2);
});
});