Ajax提交总是返回false

丹尼

我有供用户提交的表单,该表单在布局页面中以部分视图的形式呈现。我正在使用此脚本提交部分视图,并且根据我放置在该视图上的breackpoint始终返回false,并且数据确实提交给了Db,并且表单未清除其上的数据。我在提交按钮上也有一个小脚本,但是breackpoint从未到达那里。这是我正在使用的脚本:

 $('#contact').submit(function () {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function (result) {
            $('#contact').html(result);
        }
    });
    return false;
});

$("#Send").bind('click', function (event) {
    $("#contact").submit();
});
麦坎

您是在告诉它return falseAjax是异步运行的,因此代码将仅启动Ajax,然后转到下一步-返回false。没有时间打success(返回假之前)。

相反,我会做这样的事情:

$('#contact').submit(function (e) {
    e.preventDefault(); //prevents the submit
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        datatype : 'html',
        success: function (result) {
            $('#contact').html(result);
        }
    });
});

您还可以通过添加option选择同步运行Ajax async: false,但是不建议这样做。

正如A. Wolff在评论中所提到的,return false并且e.preventDefault本质上是做同样的事情。

但是,如果Ajax不成功,则该处理程序将永远不会被触发。也许为其添加处理程序error将澄清错误的真正来源:

$.ajax({
    url: this.action,
    type: this.method,
    data: $(this).serialize(),
    datatype : 'html',
    success: function (result) {
       $('#contact').html(result);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
       alert("Status: " + textStatus + " Error: " + errorThrown);  
    }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章