0

我有一个网页,我正在使用 .ajax 将变量发送到 php 脚本。php 页面正在加载到浏览器中,就像我正在导航到它一样。该脚本正在正确加载数据,所以我的问题是停止导航并将用户保持在原始页面上。我的表格的代码在这里:

echo "<form method='post' action='addTask.php' id='myform'>\n";
echo "<input name='addtask' id='addtask' maxlength='64'/><br/>\n";
echo "<input type='submit' name='submit' id='submit' value='Add Task'/>\n";
echo "</form>\n";

我的 jquery 的代码在这里:

    $(function(){
    $('#myform').submit(function(e){
        e.stopPropagation();
        $.ajax({
            url: 'addTask.php',
            type: 'POST',
            data: {},
            success: alert("Success")
            });
        });
    });

我尝试过:e.preventDefault()、e.stopPropagation() 并返回 false。任何帮助表示赞赏。

        $("#submit").click(function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "addtask.php",
            data: { }
        })
        .done(function() {
            alert( "success" );
        })
        .fail(function() {
            alert( "error" );
        });

$(function(){
    $('#myform').submit(function(e){
        e.preventDefault();
        $.ajax({
            url: 'addTask.php',
            type: 'POST',
            data: {},
            success: function(){alert("Success")}
        });
    });
});
4

2 回答 2

2

I had success preventing the form submission by returning false after the ajax call.

$(function () {
    $('#myform').submit(function (e) {
        $.ajax({
            url: 'addTask.php',
            type: 'POST',
            data: {},
            success: alert("Success")
        });
        return false;
    });
});

http://jsfiddle.net/5c3n2/

Edit:

The code above demonstrates how return false prevents form submission. However, as mentioned by gloomy.penguin, success should be a function. Also, since the call will never succeed on jsFiddle, I added complete.

$(function () {
    $('#myform').submit(function (e) {
        $.ajax({
            url: 'addTask.php',
            type: 'POST',
            data: {},
            success: function() {alert("Success");},
            complete: function() {alert("Completed");}
        });
        return false;
    });
});

http://jsfiddle.net/5c3n2/2/

于 2013-11-07T21:40:57.933 回答
-1

尝试阻止提交按钮的默认设置:

$('input#submit').click(function(e){
    e.preventDefault();
    //submit your form
});
于 2013-11-07T21:38:42.223 回答