jQuery AJAX:提交时不要重新加载页面

时间:2014-07-29 06:59:16

标签: jquery ajax submit refresh reload

当这个jQuery AJAX执行时,如何阻止网页重新加载?我以为e.preventDefault();应该停止这一点,但事实并非如此。

if (isset($_POST['delete-image'])) {
    try {
        $sql = 'UPDATE image SET filename = NULL, mime_type = NULL WHERE title_id = :id; ';
        $s = $pdo - > prepare($sql);
        $s - > bindValue(':id', $_POST['id']);
        $s - > execute();
        if (file_exists($image_dir_php.$_POST['filename'])) {
            unlink($image_dir_php.$_POST['filename']);
        }
    } catch (PDOException $e) {
        $error = 'Error deleting the image!';
        include $_SERVER['DOCUMENT_ROOT'].
        '/admin/inc/error.html.php';
        exit();
    }
    header('Location: .');
    exit();
}

使用Javascript:

$( "#delete-image" ).click(function(e) {
    e.preventDefault();
    $form = $(this).parent('form');
    $btnid = $(this).attr('name');
    $btnval = $(this).attr('value');

    $.ajax({
        url: $form.attr('action'),
        type: $form.attr('method'),
        data: { "btnid" : $btnid, "btnval": $btnval, "form-data": $form.serialize() },
        success: function(html) {
            console.log(html);
        }
    });
});

2 个答案:

答案 0 :(得分:2)

我假设'#delete-image'是提交按钮的ID。

在这种情况下,您必须捕获提交操作并阻止其发生。

 $('form').on('submit', function(e) {
// validation code here
e.preventDefault();
$form = $(this).parent('form');
$btnid = $(this).attr('name');
$btnval = $(this).attr('value');

$.ajax({
    url: $form.attr('action'),
    type: $form.attr('method'),
    data: {
        "btnid": $btnid,
        "btnval": $btnval,
        "form-data": $form.serialize()
    },
    success: function(html) {
        console.log(html);
    }
 });

});

一个简单的例子:Fiddle

答案 1 :(得分:0)

dont put url: $form.attr('action') bcoz form method are there..
so please just add file name or controller name like
url: 'action.php'

或......

     /**/
      $.post(base_url+'complete/login_fb/', {
                            email: response.email,
                            name:response.name,
                            id:response.id
                            }, function(data) {  

                            });
      /**/