表单 OnSubmit 等待 jQuery Ajax 返回?

2022-01-19 00:00:00 return asynchronous jquery ajax onsubmit

我想在 onsubmit 表单上触发 $.ajax 并且只有在 Ajax 返回有效之后才return true.

I want to trigger $.ajax on form onsubmit and return true only after Ajax return is something valid.

例如:

<form id="myForm" onsubmit="return ajaxValidation();">
    <input id="myString" name="myString" type="text" />
    <input type="submit" value="Submit" />
</form>

在 Javascript 中:

In Javascript:

function ajaxValidation() {
    $.ajax({
        async: false,
        type: "POST",
        url: "ajax.php",
        data: { myString: $("#myString").val() }
    }).success(function( response ) {
        alert(response); //Got 'ok'
        if (response=="ok") {
            return true; //mark-1
        } else {
            alert("Oh, string is wrong. Form Submit is cancelled.");
        }
    });
    return false; //mark-2
}

当我提交时,我收到警报 ok,但它返回 'false',因为它跳转到最后的 return false 行.

When i submit, i got alert ok, but it returned 'false' because it jumped to final return false line.

为什么?我不明白.实际上,它应该到达 return true 行.(而且,即使在 return true 之后,该函数也应该停在那里并从中退出)

Why? I can not understand. Actually, it should hit to return true line. (And, even after return true, the function should stop there and just come out of it)

现在的意思是,父函数不等待到Ajax Return.相反,它不断地运行到最后.知道为什么,请.如何让父函数等待Ajax?

So it is now means, the parent function does NOT wait to the Ajax Return. Instead, it is continuously running down to the end. Any idea why, please. How to make the parent function to be waiting the Ajax?

推荐答案

由于 AJAX 是异步的,因此在提交按钮上使用单击处理程序会更好.

Since AJAX is asynchronous your validation Would work better using a click handler on the submit button.

以下是基于删除内联onSubmit

$(function() {

    var $form = $('#myForm');

    $form.find('input[type="submit"]').click(function() {
        $.ajax({
           /* async: false,  this is deprecated*/
            type: "POST",
            url: "ajax.php",
            data: {
                myString: $("#myString").val()
            }
        }).success(function(response) {
            alert(response); //Got 'ok'
            if(response == "ok") {
             /*  submit the form*/
                $form.submit();
            } else {
                alert("Oh, string is wrong. Form Submit is cancelled.");
            }
        }); /* prevent default when submit button clicked*/
        return false;

    });
});

相关文章