提交AJAX Post onchange

时间:2017-02-20 22:23:53

标签: javascript jquery ajax forms

我正在试图弄清楚为什么这不起作用,我不希望有一个提交按钮来点击,如果我有一个,它确实有效,而是我使用onchange="this.form.submit()"和那个帖子通常会形成的形式,而不是AJAX背景样式,我没有编写ajax部分的代码,我发现它并使其适用于我的情况,但据我所知$('#ajaxform').submit(function (),提交是否提交?为什么onchange="this.form.submit()"<input type="submit" />不是同一类型的提交?我错过了什么?

    <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>

1 个答案:

答案 0 :(得分:5)

在表单中使用:

<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
        }
    });
}