2014-04-17 56 views
0

我正在使用下面的代碼來運行使用AJAX的PHP文件。它工作正常,因爲它應該。默認表單操作後運行ajax?

但是,AJAX代碼的形式有一個default action。例如<form action="index.php">

我的AJAX代碼是這樣的:

   <script> 
     $('#select').change(function(){ 
      var selectedValue = $(this).val(); 
      if (selectedValue === 'Yes') { 
        $(function(){ 
     $('form').submit(function(e){ 
     var thisForm = $(this); 
     //Prevent the default form action 
     e.preventDefault(); 
      //Post the form to the send script 
      $.ajax({ 
       type: 'POST', 
       url: 'mySecond.php', 
       data: thisForm.serialize(), 
       //Wait for a successful response 
     }); 
     }) 
    }); 
      } else { 

      } 
     }); 
</script> 

我知道e.preventDefault();意味着它將擺脫默認的形式作用的,它只會執行AJAX調用。

那麼,有什麼辦法可以同時執行AJAXdefault form action?或者可能一個接一個?

P.S.我確實刪除了e.preventDefault();,它會停止AJAX呼叫的工作!

任何幫助,將不勝感激。

謝謝

+0

不能執行這兩個AJAX和自'默認形式action'將刷新當前頁面的'默認形式action'(或重定向到另一頁) – hindmost

回答

1

不一樣。

您不能執行默認表單操作,然後執行Ajax,而無需設置作爲對錶單提交的響應的頁面,以在加載時發出Ajax請求。

您不能執行Ajax請求,然後允許默認表單提交繼續,因爲Ajax是異步的,所以在表單提交被觸發前它不會完成。

您可以取消默認表單操作,執行Ajax請求,然後(在Ajax請求的響應處理程序中)以編程方式提交表單(通過調用其submit()方法)。

儘管使用普通表單提交作爲單個請求來執行這兩項任務,但完全不用打擾Ajax,你可能會更好。

+0

這是有道理的。任何一個例子的機會? – user3454730

+0

'ref_to_form.submit()' – Quentin

+0

更多的細節會很棒!那去哪裏?那是什麼意思? – user3454730

0

我不知道爲什麼會ü做,但肯定有一種方法:

<script> 
    var continue = true; 
    $('#select').change(function(){ 
     var selectedValue = $(this).val(); 
     if (selectedValue === 'Yes') { 
       $(function(){ 
       $('form').submit(function(e){ 
        var thisForm = $(this); 
        //Prevent the default form action 
        if(continue){ 
         e.preventDefault(); 

         //Post the form to the send script 
         $.ajax({ 
          type: 'POST', 
          url: 'mySecond.php', 
          data: thisForm.serialize(), 
          //Wait for a successful response 
          success: function(data){ 
            continue = false;  
            $(thisForm).submit(); 
          } 
         }); 
        } 
       }) 
      }); 
     } else { 

     } 
    }); 
</script> 
+0

您的代碼中存在語法錯誤。 – user3454730

+0

我沒有標記和完整的代碼,但它說的語法錯誤?可能會很快得到它:) –

+0

第一行。 'var continue = true;' – user3454730

0

下面嘗試。在完成的回調中執行ajax調用。

 <button id="btnSave" type="submit" formaction="Save">Save</button>   
    $('#btnSave').click(function (e) { 
var thisForm = $(this).closest(form).serialize(); 
       $.ajax({ 
        url: '#', 
        type: 'GET', 
        cache: false 
       }).done(function(result) { 
         CallMySecond(thisForm);   
       });    

     }); 
function CallMySecond(data){ 
$.ajax({ 
       type: 'POST', 
       url: 'mySecond.php', 
       data: thisForm.serialize() 
}); 
}