简体   繁体   English

jQuery表单提交功能中的AJAX调用

[英]AJAX call in jQuery form submit function

I'm using ASP.NET MVC. 我正在使用ASP.NET MVC。 So I have a form on my page: 所以我的页面上有一个表格:

<form id="MyForm" name="MyForm" method="post" action="http://www.mysite.com">
    <input id="hdnType" name="hdnType" type="hidden" />
</form>

I'm using the jQuery submit action to do some validation before the form is posted. 我正在使用jQuery提交操作在表单发布之前进行一些验证。 I also need to make an AJAX call to set "hdnType" based on other values from several dropdowns that I didn't include in this example: 我还需要进行AJAX调用,以基于以下示例中未包括的多个下拉菜单中的其他值来设置“ hdnType”:

$('#MyForm').submit(function()
{
    if (!ValidForm())
        return false;

    $.ajax({
        type: "POST",
        url: '/Home/GetType',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response)
        {
            $('#hdnType').val(response);
        }
    });

    return true;
}

Everything in the submit() function is supposed to run before the form posts. Submit()函数中的所有内容都应在表单发布之前运行。 This was working correctly before I added that AJAX call, but now when the code reaches my AJAX call, the form posts before I can set "hdnType". 在添加该AJAX调用之前,此方法正常工作,但是现在当代码到达我的AJAX调用时,该表单会在我可以设置“ hdnType”之前发布。

Is there a way around this? 有没有解决的办法?

The ajax call has a parameter async. ajax调用具有参数async。 By default it is true. 默认情况下为true。 This causes execution to not be held and the function to complete. 这将导致不保留执行且功能无法完成。 Try changing it to 尝试将其更改为

$.ajax({
    async:false,
    type: "POST",
    url: '/Home/GetType',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response)
    {
        $('#hdnType').val(response);
    }
});

This may be a poor practice as it will freeze the browser until it is done. 这可能是一个不好的做法,因为它将冻结浏览器直到完成。 Consider using an asyc call back function as Dave suggests 考虑使用Dave建议的asyc回调函数

The success function is called asynchronously, after the ajax call gets a response. 在ajax调用获得响应之后,将异步调用成功函数。 If you want to set hdnType before the form is posted you'd have to move that call outside the $.ajax call. 如果要在发布表单之前设置hdnType,则必须将该调用移至$ .ajax调用之外。 It looks like you need to get the result for hdnType from your POST action first, in a separate function, then call submit on the form. 看来您需要首先从POST操作中的单独函数中获取hdnType的结果,然后在表单上调用Submit。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM