请帮我解决这个问题...
我必须将值传递到 php 文件进行保存,但如果选中了复选框,则必须使用第一个的返回值执行第二个 jquery post。但似乎第二个 jquery 帖子首先被执行,这是我的代码:
if($action=="save_prod")
{
var remember = document.getElementById('chk');
var $suppid=document.getElementById('supp').value;
var $categlist=document.getElementById('categlist').value;
var $prodname=document.getElementById('prodname').value;
var $proddesc=document.getElementById('proddesc').value;
$.post(baseurl+'index.php/main/newproduct',{"categlist" : $categlist,"prodname" : $prodname," proddesc" : $proddesc,"supp" : $suppid},function(response)
{
$lastid=response;
if($lastid != 0)
{
alert("Product has been saved with ID=" + $lastid);
document.getElementById('resp').style.display='none';
document.getElementById('fade').style.display='none';
window.location.href=baseurl +"index.php/main/mgtprods/?key="+ $suppid;
}
});
if (remember.checked)
{
//alert($lastid);
$.post(baseurl+'index.php/main/newitem',{"prodlist" : $lastid ,"itlist" : 0,"itcost" : 0, "supp" : $suppid, "itname" : $prodname, "itunit" : "pc" },function(response)
{
document.getElementById('resp').style.display='none';
document.getElementById('fade').style.display='none';
//window.location.href=baseurl +"index.php/main/mgtprods/?key="+ $suppid;
});
}
}
非常感谢!
最佳答案
jQuery ajax 函数($.ajax()
、$.get()
、$.post()
...)全部返回 Deferred包装底层 jqXHR
对象的对象。
利用 Deferred.then()
链接两个异步调用的函数:
//your first $.post :
$.post(...)
.then(function(){
if (remember.checked) {
//your second $.post :
$.post(...);
}
});
这样使用时,仅当第一次调用成功时才会调用第二个函数(如果第一次调用导致错误,则不会触发任何内容)。
<小时/>您的第一个回调包含重定向:window.location.href=baseurl +"index.php/main/mgtprods/?key="+ $suppid;
。您必须更准确地选择何时执行此重定向。
这里有一种方法,可以在选中 remember
后在第二次调用后触发重定向,或者如果未选中 remember
则在第一次调用后触发重定向,方法是链接 延迟
对象:
$.post(... /* remove the redirection from the first callback */)
.then(function(){
if (remember.checked) {
//your second $.post : return the Deferred corresponding to this call
return $.post(... /* remove the redirection from the second callback */);
} else {
// else, return the first Deferred object :
return this;
}
}).then(function(){
/* do your redirection here : */
window.location.href=baseurl +"index.php/main/mgtprods/?key="+ $suppid;
});
关于php - 2 个连续的 JQuery 帖子,第二个先执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18736063/