2013-07-03 26 views
0

我首先想要在數據庫中插入一些Ajax數據,這工作正常,但提交標準的HTML表單失敗:$(「#foo 「)。提交(); 控制檯消息循環不已: -/提交表單值與jQuery的作品,但無法在成功後提交標準的HTML表格

<script type="text/javascript"> 
// variable to hold request var request; 
// bind to the submit event of our form $("#foo").submit(function(event){ 
    // abort any pending request 
    if (request) { 
     request.abort(); 
    } 
    // setup some local variables 
    var $form = $(this); 
    // let's select and cache all the fields 
    var $inputs = $form.find("input, select, button, textarea, text, hidden"); 
    // serialize the data in the form 
    var serializedData = $form.serialize(); 

    // let's disable the inputs for the duration of the ajax request 
    $inputs.prop("disabled", true); 

    // fire off the request to /form.php 
    request = $.ajax({ 
     url: "/insert_payment_data.php", 
     type: "post", 
     data: serializedData 
    }); 

    // callback handler that will be called on success 
    request.done(function (response, textStatus, jqXHR){ 
     // log a message to the console   
    console.log("Hooray, it worked!"); 
    $("#foo").submit(); 
}); 

    // callback handler that will be called on failure 
    request.fail(function (jqXHR, textStatus, errorThrown){ 
     // log the error to the console 
     console.error(
      "The following error occured: "+ 
      textStatus, errorThrown 
     ); 
    }); 

    // callback handler that will be called regardless 
    // if the request failed or succeeded 
    request.always(function() { 
     // reenable the inputs 
     $inputs.prop("disabled", false); 
    }); 

    // prevent default posting of form 
    event.preventDefault(); }); 

</script> 

這已經快把我逼瘋了:-(

回答

1

這是正常的:

$("#foo").submit(); 

這條線在你request.done方法結束時觸發表單的提交,這可能觸發了AJAX請求,這就觸發了request.done ...等等:-)

我會做的(嘗試)是刪除該行,並且還刪除底部的event.preventDefault();聲明,以便在完成AJAX請求後,您的提交將像往常一樣運行。

+0

你也可以不提交#foo如果你已經發布了表單,但是如果你想發佈額外的信息,那麼就不要'返回false',這樣你就可以做你的Ajax的東西和**然後**正常發佈表單。 –

+0

另一個請求是到另一個域,這就是爲什麼我想使用通常的過程。我知道無法將AJAX請求發送到其他域。我怎樣才能打破這個循環? –

+0

確實這是一個很好的理由:-)請看我更新的答案,我認爲它會解決問題。 –