2017-02-20 75 views
0

我想弄清楚爲什麼這不起作用,我不想有一個提交按鈕來點擊,它確實工作,如果我有一個雖然,而是我使用onchange="this.form.submit()",並且該帖子像通常那樣的表單,不是AJAX背景風格,我沒有編碼ajax部分,我發現它,並使其適用於我的情況,但據我所知$('#ajaxform').submit(function(),提交是提交?爲什麼不是onchange="this.form.submit()"<input type="submit" />是同一類型的提交?我錯過了什麼?提交AJAX Post onchange

<form method="post" action="~/getAJAX.cshtml" id="ajaxform" name="form"> 
     @* -------- Div to hold form elements -------- *@ 
     <div class="reportDateDiv"> 

      @* -------- Text --------- *@ 
      <a class="blackColor fSize18 RPtxt">Reporting Period</a> 

      @* -------- Start day box -------- *@ 
      <input type="text" name="inputDate" spellcheck="false" class="datepickerS metricDateTextbox capitalFirst" 
        onchange="this.form.submit()" value="@inputDate" autocomplete="off" placeholder="@placeholderStartDate.ToString("MMM d, yyyy")" readonly="readonly" /> 

      @* -------- Text --------- *@ 
      <a class="blackColor fSize16 RPtxt RPtxtTo">to</a> 

      @* -------- End day box --------- *@ 
      <input type="text" name="endDate" spellcheck="false" class="datepickerE metricDateTextbox capitalFirst" 
        onchange="this.form.submit()" value="@endDate" autocomplete="off" placeholder="@noEndDate.ToString("MMM d, yyyy")" readonly="readonly" /> 

     </div> 
    </form> 

    <script type="text/javascript"> 
     $('#ajaxform').submit(function() { // catch the form's submit event 
      $.ajax({ // create an AJAX call... 
       data: $(this).serialize(), // get the form data 
       type: $(this).attr('method'), // GET or POST 
       url: $(this).attr('action'), // the file to call 
       success: function (response) { // on success.. 
        $('#here').html(response); // update the DIV 
       } 
      }); 
      return false; // cancel original event to prevent form submitting 
     }); 
    </script> 
+0

您可以編輯您的說明文字,所以我們可以理解它?你想要什麼?而你取而代之的是什麼? –

+0

如果我從我的輸入文本框中刪除'onchange =「this.form.submit()」',並在我的表單中放置一個提交按鈕,所有東西都可以正常工作,它會在後臺獲取我想要的內容並將其顯示爲AJAX但是,與onchange提交的東西,它不會做的AJAX的一部分,它只是張貼的形式,如果沒有AJAX,它會重新加載頁面。 @ChrisG –

+0

我可以證實這一點;顯然在窗體上調用'submit()'會跳過'onsubmit'處理程序。解決方案是將ajax調用包裝在函數中,並在'onchange'處理程序中調用它。 https://developer.mozilla.org/en/docs/Web/API/HTMLFormElement/submit –

回答

2

使用此表單中的:

<input ... onchange="mySubmit(this.form)" ... > 

更改腳本這樣的:

function mySubmit(theForm) { 
    $.ajax({ // create an AJAX call... 
     data: $(theForm).serialize(), // get the form data 
     type: $(theForm).attr('method'), // GET or POST 
     url: $(theForm).attr('action'), // the file to call 
     success: function (response) { // on success.. 
      $('#here').html(response); // update the DIV 
     } 
    }); 
} 
+0

絕對真棒!謝謝你的幫助! –

+0

你讓我的一天!謝謝! –

+0

太棒了! jQuery,JS和所有已經改變,很難跟上,所以謝謝你的時間和sollution! –