提交表单不会在 jquery ajax 调用中停止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/804946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:48:57  来源:igfitidea点击:

submit form does not stop in jquery ajax call

jqueryformssubmit

提问by Ray

I got following code :

我得到以下代码:

$.ajax({
    type: "POST",
    async: false,              
    url: "CheckIdExist",
    data: param,
    success: function(result) {
        if (result == true){
            return false;
        }                                 
    },
    error: function(error) {
        alert(error);
        return false;
    }
});

if ajax return value is true, form needs to stop submit.

如果ajax返回值为true,则表单需要停止提交。

but it does not stopping submit form.

但它不会停止提交表单。

any help please.

请任何帮助。

回答by DarkWulf

I assume you have something like:

我假设你有这样的事情:

form.submit(function(event) {
    $.ajax(...);
});

You want to return false(or call event.preventDefault()) in the event handling function itself, and not in the AJAX call, such as:

您想return false(或调用event.preventDefault())在事件处理函数本身中,而不是在 AJAX 调用中,例如:

form.submit(function(event) {
    event.preventDefault();
    $.ajax(...);
});

回答by Jim Penny

A slight variation of this question is: I want to use jquery and ajax to present an error message to a user, but then to do normal processing if there is no error.

这个问题的一个细微变化是:我想使用 jquery 和 ajax 向用户显示错误消息,但如果没有错误,则进行正常处理。

Suppose method "check" returns a response that is empty if there is no error, and has the error(s) in it if there are any.

假设方法“check”返回一个响应,如果没有错误,则返回一个空响应,如果有错误,其中包含错误。

Then you can do something like this in your ready function:

然后你可以在你的就绪函数中做这样的事情:

$("#theform").submit(function() {
    var data = { ... }
    $.get('/check', data,
        function(resp) {
            if (resp.length > 0) {
                $("#error").html(resp);
            } else {
                $("#theform").unbind('submit');
                $("#theform").submit();
            }
    });
    event.preventDefault();
});

So, how does it work? When the outer submit function is triggered, it builds the data needed for the AJAX call (here the higher level function get). The call is scheduled, and the main thread of operation immediately continues, but the submit is unconditionally stopped, so nothing apparent happens.

那么它是怎样工作的?当外部提交函数被触发时,它会构建 AJAX 调用所需的数据(这里是更高级别的函数 get)。调用被调度,操作的主线程立即继续,但提交被无条件停止,所以没有任何明显的反应。

Some time passes, and the AJAX call returns the result of the request. If non-empty, the result is shown to the user.

一段时间过去了,AJAX 调用返回了请求的结果。如果非空,则将结果显示给用户。

If the response is empty, however, the submit function is unbound. This prevents the ssytem from making an extra call through the outer submit function. The inner submit function is called. This triggers an actual form submission to the form's target, and life goes on as expected.

但是,如果响应为空,则提交功能未绑定。这可以防止系统通过外部提交函数进行额外调用。调用内部提交函数。这会触发对表单目标的实际表单提交,并且生命按预期进行。

回答by ólafur Waage

You need to do a callback.

你需要做一个回调。

This entry in the FAQhelped me a lot when I had this exact problem.

当我遇到这个确切的问题时,FAQ 中的这个条目对我帮助很大。

getUrlStatus('getStatus.php', function(status) {
    alert(status);
});

function getUrlStatus(url, callback) {
    $.ajax({
        url: url,
        complete: function(xhr) {
            callback(xhr.status);
        }
    });
}

The reason for that is that you can not return in an AJAX function.

原因是你不能在 AJAX 函数中返回。

The code above does not work as desired due to the nature of asynchronous programming. The provided success handler is not invoked immediately, but rather at some time in the future when the response is received from the server. So when we use the 'status' variable immediately after the $.ajax call, its value is still undefined.

由于异步编程的性质,上面的代码不能按预期工作。提供的成功处理程序不会立即调用,而是在将来从服务器收到响应时调用。所以当我们在 $.ajax 调用之后立即使用 'status' 变量时,它的值仍然是未定义的。

回答by cgp

You can't put this code in a function or in the onsubmit of a form, the success function returns it's result returning to the jQuery ajax context, NOT the form submit context.

您不能将此代码放在函数或表单的 onsubmit 中,成功函数返回它的结果返回到 jQuery ajax 上下文,而不是表单提交上下文。

回答by VolkerK

In this case you need to perform a synchronous http request, i.e. you have to set the async optionto false.
In your version the httpxmlrequest is asynchronous. It might be finished long after your onsubmit handler has returned and the onsuccess callback is invoked out of context of the onsubmit handler.
The "return false" will be the return value of the anonymous function function(result) {... } and not the return value of the onsubmit handler.

在这种情况下,您需要执行同步 http 请求,即您必须将 async 选项设置为 false。
在您的版本中,httpxmlrequest 是异步的。它可能在您的 onsubmit 处理程序返回后很长时间完成,并且 onsuccess 回调在 onsubmit 处理程序的上下文之外被调用。
“return false”将是匿名函数 function(result) {... } 的返回值,而不是 onsubmit 处理程序的返回值。

回答by Patrik Potocki

I had this problem also but solved it by changing the input type="submit" to type="button" and then just do your ajax request

我也有这个问题,但通过将 input type="submit" 更改为 type="button" 然后执行您的 ajax 请求来解决它

   $("input#submitbutton")
    {
                          $.ajax(
                        {                         type: "POST",
                             async: false,              
                            url: "CheckIdExist",
                             data: param,
                            success: function(result) {
                                 if (result == true){
                                    //TODO: do you magic
                                 }                      
                                 else
                                  $("form").submit();           
                             },
                             error: function(error) {
                                alert(error);
                                return false;
                            }
                        });
    });