使用Jquery(ajax)阻止页面重新加载的最佳方法是什么?

时间:2013-09-13 13:11:01

标签: php jquery html ajax

总结:我有一个:

1)主页(Main.php) 2)简单的.js脚本文件(dashboard.js) 3)另一个简单的.php文件(form1.php) 4)process.php,一个处理.js文件(process.php)发送的信息的文件

就像tumblr一样,我正在尝试重新创建相同的“导航”体验 - 单击几个选项,用新代码替换主面板,并在填写某个表单时,将该信息发送给BD并将结果显示在Main.php

一切进展顺利,但最后一步。单击导航按钮(main.php)后,通过javascript(dashboard.js + form1.php)填充新表单,填写该表单,我单击按钮而不是不重新加载页面(jquery-> ajax) ,它将我发送到process.php文件并向我显示结果。

我试过不用“return false”和“event.preventdefault()”重新加载,结果仍然相同。

JS代码

        $('form.ajax').on('submit', function() {
    event.preventDefault();
    var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};

    that.find('name').each(function(index, value) {

        var that = $(this),
        name = that.attr('name'),
        value = that.val();

        data[name] = value;

    });


    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(html){
                    event.preventDefault();
                    $("ol#list-feed").append(html);
                    document.getElementById('set-width1').value='';
                    document.getElementById('tags').value='';

                }


    });
    event.preventDefault();
    return false;
});

4 个答案:

答案 0 :(得分:3)

您尚未定义event

$('form.ajax').on('submit', function(event) {
    event.preventDefault();
    //...
});

答案 1 :(得分:0)

您需要将第一行更改为:

$('form.ajax').on('submit', function(event) {

否则函数内的event变量未定义。

答案 2 :(得分:0)

试试这个

$('form.ajax').on('submit', function(event) {
    event.preventDefault();
    //do other works here

}

或从任何地方删除 event.preventDefault(),在此功能结束之前,只需使用 return false

答案 3 :(得分:0)

这应该有效

 $('form.ajax').on('submit', function(event) {