$ .post成功$ .post

时间:2013-03-16 04:19:30

标签: jquery ajax

有没有办法在$ .post的成功回调中再次使用$ .post。如果第一个$ .post不成功,我会要求提示。如果确认,则再次执行另一个$ .post

我的代码如下

postvars = {
                order_no:order_no,
                tracking_no:tracking_no,
                continue_submit: false
            };  

url =  '../shipment/shipment_submit_order_status_ajax';  

  $.post(url, postvars, function(data1) {
        if(data1.status == "success")
        {
            alert("Order submitted 1");
        }
        else if(data1.status != "success")
        {
            var r = confirm("The Order is NOT ready to be shipped. Please check the order again. Are you sure you want to continue to ship this?");
            if(r)
            {
                //Submit order
                postvars = {
                    order_no:order_no,
                    tracking_no:tracking_no,
                    continue_submit: true
                };  

                url =  '../shipment/shipment_submit_order_status_ajax';

                $.post(url, postvars, function(data) { 
                    if(data.status == "success")
                    {
                        alert("Order submitted 2");
                    }
                }, 'json');  
            }
        }

    }, 'json');

它正在执行两个调用,而不是在执行第二个ajax调用之前首先提示确认对话框。有人有任何解决方案?提前致谢

2 个答案:

答案 0 :(得分:2)

我建议您在jQuery中使用延迟对象:

function ajaxMe(data){
    var df = $.Deferred();
    $.post('my_const_url', data, function(resp){
        if(resp.status !== 'success'){
            df.resolve(other_data);
        }else{
            df.reject(other.data);
        }
    }, 'json');
    return df.promise();
}

ajaxMe(postvars).done(function(response_data){
    ajaxMe(whatever_you_want);
}).fail(function(){
    var r = confirm("Do you really want it ?");
    if(r){
       ajaxMe(some_data);
    }
});

答案 1 :(得分:-2)

而不是'if(r)'使用'if(true === r)'

因为在javascript中'if(r)'表示是否定义了变量'r'。在这种情况下,定义了该变量'r',因此满足'if'部分。