2016-03-02 28 views
1

我想在不刷新页面的情况下删除数据库中的数据。我的代码正在工作,但删除产品后需要刷新页面。我想是这样this删除数据库中的数据而不重新加载页面

这里是我的js代码:

<script> 
    $(document).on('click', '.delete-it', function() { 
     var id = $(this).attr('delete-id'); 
     bootbox.confirm("Are you sure?", function(result) { 
      if (result) { 
       $.ajax({ 
        type: "POST", 
        async: false, 
        url: "delete_product.php", 
        data: { 
         object_id: id 
        }, 
        dataType: 'json', 
        success: function(data) { 
         location.reload(); 
        } 
       }); 
      } 
     }); 
     return false; 
    }); 
</script> 

和delete_product PHP代码:

<?php 
// check if value was posted 
if($_POST){ 



    // get database connection 
    $database = new Database(); 
    $db = $database->getConnection(); 

    // prepare product object 
    $product = new Product($db); 

    // set product id to be deleted 
    $product->id = $_POST['object_id']; 

    // delete the product 
    if($product->delete()){ 
     echo "Object was deleted."; 
    } 

    // if unable to delete the product 
    else{ 
     echo "Unable to delete object."; 

    } 
} 
?> 

请告诉我一个方法,使之!

+0

您可以在成功发布后从页面中移除html元素。它看起来像你可以利用删除ID来完成这一点。 – spaniol6

+2

在删除的成功回调中,发出一个ajax调用,将所有产品从数据库中取出并将结果放入您的HTML – mhodges

+0

下面是使用delete-id的行:'echo'Delete“; ' –

回答

0

我看不出有什么地方,你在页面定向的东西,但是这是我会用什么:

<script> 
function swapContent(href, url_data, target) { 
    $.ajax({ 
     type: 'GET', 
     cache: false, 
     url: href+'?' + url_data, //add a variable to the URL that will carry the value in your i counter through to the PHP page so it know's if this is new or additional data 
     success: function (data) { // this param name was confusing, I have changed it to the "normal" name to make it clear that it contains the data returned from the request 
      //load more data to "target" value div 
      target.innerHTML = (data); // as above, data holds the result of the request, so all the data returned from your results.php file are in this param but please see below 
     } 
    }) 

} 
    $(document).on('click', '.delete-it', function() { 
     var id = $(this).attr('delete-id'); 
     bootbox.confirm("Are you sure?", function(result) { 
      if (result) { 
     swapContent(base_url, url_data, target) //set variables 
    } 
     }); 
     return false; 
    }); 
</script> 

注:因为多少AJAX我用的,我把一个ajax功能通过本身

相关问题