且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC jQuery的AJAX调用处理法太晚了?

更新时间:2023-11-20 23:41:10

它看起来像你想的要求是同步的。为了让这种情况发生,你需要设置的要求,假async选项。默认是有要求,让你从Ajax调用返回请求完成之前是异步的。或者,你可以重写code,以便成功回调实际上做的工作。后者更惯用对AJAX - 但有时可能更复杂的

It looks like you want the request to be synchronous. To get this to happen you need to set the async option on the request to false. The default is to have the request be asynchronous so that you return from the ajax call before the request is complete. Alternatively, you can rewrite the code so that the success callback actually does the work. The latter is more idiomatic for AJAX -- but can sometimes be more complex.

$.ajax(
    {
    type: "POST",
    async: false,              // <- note addition
    url: "/Account/EmailExist",
    data: { 'email': emailval },
    success: function(result) {

        if (result.indb) {
            isvalid = true;

        }
    },
    error: function(error) {
        alert(error);
    }
});

$("input[type=submit]").click(function() {

    // email - check required and valid

    var form = $(this).parent('form');
    var email = $("input[name='email']");
    var emailtrim = jQuery.trim(email.val());

    SubmitIfNoEmailExists(form,emailtrim);

    return false;
});

function SubmitIfNoEmailExists(form,emailval) {

    // hit db
    $.ajax({
        type: "POST",
        url: "/Account/EmailExist",
        data: { 'email': emailval },
        success: function(result) {
            if (!result.indb) {
               form.submit();
            }
        },
        error: function(error) {
            alert(error);
        }
    });
}

修改:根据您的意见,你可能也想看看使用jQuery的验证插件作为解决所有的验证需求。

EDIT: Based on your comments, you may want to also look at using the jQuery validation plugin as a solution to all of your validation needs.