2017-02-20 122 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! –