形成的OnSubmit等jQuery的Ajax的回报?OnSubmit、jQuery、Ajax

2023-09-10 18:12:35 作者:别回头

我想触发 $。阿贾克斯的形式的onsubmit 返回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
}

当我提出,我得到警报确定,但它返回假,因为它上升到最后的返回false 行。

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

为什么呢?我不明白。事实上,它应该打到返回true 行。 (而且,即使在返回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返回。相反,它是连续运行向下到最后。知道为什么,请。如何使母公司的功能是等待阿贾克斯?

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;

    });
});
 
精彩推荐
图片推荐