如何在jquery ajax调用完成后延迟默认表单动作

How to postpone default form action after jquery ajax call finishes?

本文关键字:延迟 默认 表单 jquery ajax 调用      更新时间:2023-09-26

我有这样一个表单:

<form class='setPricetInput' method='post' action='mos.php'>
<label>
<span class = 'boldFont'>Your Selling Price:</span>
<input type='text' class='moneyFormat reqPrice' autocomplete='off' name='b2'>
</label>    
<button class='setPriceButton'>set</button>
</form>

这个jquery点击函数:

$(".setPriceButton").click(function(){
$this = $(this);
var $thisForm = $this.parent();
var $detailLine = $this.next(".detailLine");
var buyOrderID = $detailLine.find('.orderID');    
var priceSet =ParseFloat($thisForm.find('.reqPrice').val().replace('$','')).toFixed(2);
var sendData = {'value': buyOrderID, 'type': 'Buy_Order_ID'};
$.getJSON('addToSession.php',sendData);        
var sendData = {'value': priceSet, 'type': 'Price_Set'};
$.getJSON('addToSession.php',sendData);
})   

我希望默认的表单操作(most .php)后运行的jquery点击功能。jquery代码将值添加到_SESSION中,这是摩斯.php正确运行所必需的。如何将默认动作推迟到jquery函数完成后?

要在表单上运行默认提交,您需要运行.submit()。通常我们会把它放在回调中,但是因为你有2个ajax调用在运行,我们需要确保在我们提交表单之前都完成了。为此,我们在.click作用域之外创建一个变量和一个函数。接下来,我们创建一个函数,它将在每个$.getJSON完成时运行。现在,该函数第一次运行时,它将检查firstFinished是否设置为true,如果不是,则将其设置为true,以便第二次调用将提交表单。这样,如果第一个$.getJSON请求在第二个请求之后返回,您将没有问题。

var firstFinished = false,
    getJSONDone = function(){
        if(!firstFinished){
            firstFinished = true;
            return false;
        }
        $('.setPricetInput').submit();
    };
$(".setPriceButton").click(function(e){
    e.preventDefault();
    $this = $(this);
    var $thisForm = $this.parent();
    var $detailLine = $this.next(".detailLine");
    var buyOrderID = $detailLine.find('.orderID');    
    var priceSet =ParseFloat($thisForm.find('.reqPrice').val().replace('$','')).toFixed(2);
    var sendData = {'value': buyOrderID, 'type': 'Buy_Order_ID'};
    $.getJSON('addToSession.php',sendData, getJSONDone);        
    var sendData = {'value': priceSet, 'type': 'Price_Set'};
    $.getJSON('addToSession.php',sendData, getJSONDone);
});

使用$.getJSON()回调函数提交表单

    $.getJSON('addToSession.php',sendData,function()
    {
        //call this another one
          $.getJSON('url','data',function()
           {
               //in the last,make form submit.
              $( ".setPricetInput" ).submit();
    }
    );
});
http://api.jquery.com/jquery.getjson/

http://api.jquery.com/submit/