捕获生成表单的提交,以便用户在div中看到处理结果

时间:2013-03-19 16:32:45

标签: jquery ajax bind document-ready

用户点击菜单,并使用以下代码,菜单$.load()是链接的内容:

$(function() {
    $('#menu a').click(function() {
        $('#content').load(this.href);  
        return false;
    });
});

好的,现在已经加载了表单。还有一个问题。提交表单后,结果不应该将我们带到真正的action地址。所以我使用以下代码:

$('#content').on('submit', function() { // catch the form's submit event
    alert('begin');
    $.ajax({ // create an AJAX call...
        data: $(this).serialize(), // get the form data
        type: $(this).attr('method'), // GET or POST
        url: $(this).attr('action'), // the file to call
        success: function(response) { // on success..
            alert('aaaa');
            $('#content').html(response); // update the DIV
        }
    });
    return false; // cancel original event to prevent form submitting
}); 

不幸的是on未被调用且alert('begin');无效!

感谢jquery submit form and then show results in an existing div

2 个答案:

答案 0 :(得分:0)

表单上的提交事件是?换句话说,您提交的表单是否具有“内容”ID?

答案 1 :(得分:0)

我已经输入了代码的第一个代码,而不是$(document).ready(function() {});,它工作得非常完美,但是如果没有准备好文档,第二个代码就无法运行。

但为什么?我不知道。

现在可以使用的最终代码如下:

$(document).ready(function()
{
    $('#content').on('submit', 'form', function() { // catch the form's submit event
        alert('begin');
        $.ajax({ // create an AJAX call...
            data: $(this).serialize(), // get the form data
            type: $(this).attr('method'), // GET or POST
            url: $(this).attr('action'), // the file to call
            success: function(response) { // on success..
                $('#content').html(response); // update the DIV
            }
        });
        return false; // cancel original event to prevent form submitting
    }); 

});

谢谢你们的尝试。