jQuery在表单submitHandler和奇怪的重定向上等待ajax调用

时间:2021-11-29 20:37:06
function populateAndSend() {
    var _url = "..." + var1 + var2 + var3
    $.ajax({
        type: 'get',
        url: _url
    })
};

$('#tryitForm').validate({
    rules: {
        ...
    },
    submitHandler: function (form) {
        $.when(populateAndSend()).then(form.submit()); <<< does not work
    }
});

2 problems, when().then() doesn't seem to work, and when the form.submit() is fired, it redirects me back to my page, but adds var1, var2 and var3 as arguments to my page, so lets say my site url is http://localhost/home/index it would redirect me to http://localhost/home/index?var1=xxx&var2=xxx&var3=xxx?
I cant understand why this is happening?

2个问题,when()。then()似乎不起作用,当触发form.submit()时,它会将我重定向回我的页面,但是将var1,var2和var3作为参数添加到我的页面,所以让我说我的网站网址是http:// localhost / home / index它会将我重定向到http:// localhost / home / index?var1 = xxx&var2 = xxx&var3 = xxx?我不明白为什么会这样?

Final version:

// function call, to pass message to telegram bot
function populateAndSend() {
    var _url = "..." + var1 + var2 + var3

    return $.ajax({
        type: 'get',
        url: _url
    })
};
// form validation
$('#tryitForm').validate({
    rules: {
        xxx
    },
    submitHandler: function (form) {
        populateAndSend();
        return false;
    }
});

1 个解决方案

#1


3  

You don't need to call form.submit() in the submit handler, the form submission is being done using $.ajax(). Change to:

您不需要在提交处理程序中调用form.submit(),表单提交是使用$ .ajax()完成的。改成:

$('#tryitForm').validate({
    rules: {
        ...
    },
    submitHandler: function () {
        populateAndSend();
        return false;
    }
});

return false; in the submit handler tells the validation plugin not to do normal form submission.

返回虚假;在提交处理程序中告诉验证插件不要进行正常的表单提交。

#1


3  

You don't need to call form.submit() in the submit handler, the form submission is being done using $.ajax(). Change to:

您不需要在提交处理程序中调用form.submit(),表单提交是使用$ .ajax()完成的。改成:

$('#tryitForm').validate({
    rules: {
        ...
    },
    submitHandler: function () {
        populateAndSend();
        return false;
    }
});

return false; in the submit handler tells the validation plugin not to do normal form submission.

返回虚假;在提交处理程序中告诉验证插件不要进行正常的表单提交。