【问题标题】:AJAX call inside the onsubmit of a form submits the form despite return false尽管返回 false,表单的 onsubmit 内的 AJAX 调用仍会提交表单
【发布时间】:2015-09-13 12:02:51
【问题描述】:

我有只用于 ajax 调用的表单。我从 onsubmit 进行 ajax 调用,以便能够对必填字段使用自动检查。即使我在提交时返回错误,表单也会提交。我注释掉了进行ajax调用的语句,表单不提交。我在下面给出了我使用的 from。为什么我不能阻止表单提交。

<form action="" method="post" onsubmit="ajaxReq (); return false;">
    <input type="hidden" name="type" value='something'>
    <input type="text" name="testText" required>
    <input type="submit" value="AJAX_TEST">
</form>

ajaxReq 函数如下

//I will be using the data from the form inside data as the data of the ajax call
//Currently data in the form is ignored
function ajaxReq() {
    var ajaxSettings = {
        'url' : '',
        'async' : false,
        'type' : 'POST',
        'data' : {
            'type' : 'SOME_TYPE'
        },
        'success' : function(data) {
            data = JSON.parse(data);

            //emptying this part did not change the result
            //will be using data here

        }
    };

    $.ajax(ajaxSettings);

    return false;

}

【问题讨论】:

  • 查看浏览器的 JS 控制台。那里可能有错误。 JS 很可能在返回 false 之前就中止了。
  • @Quentin 你是对的。唯一的问题是链接到 jquery 是错误的。因此,正如您所说,它在返回 false 之前失败。
  • @Quentin 您能否以合适的格式添加您的评论作为答案?

标签: javascript ajax forms onsubmit


【解决方案1】:

为您的表单提供一个 ID,例如id="myform" 然后:

$('#myform').submit(function(e) {
  e.preventDefault();
  ajaxReq();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多