javascript - 从数据库中删除数据而不重新加载页面

标签 javascript php jquery ajax

我想从数据库中删除数据而不刷新页面。我的代码可以正常工作,但删除产品后需要刷新页面。我想要类似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.";

    }
}
?>

请告诉我一种制作方法!

最佳答案

我没有看到您在页面中定位某些内容的地方,但这就是我会使用的:

<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函数

关于javascript - 从数据库中删除数据而不重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35759221/

相关文章:

javascript - DatePicker react 是否将 "value"属性作为输入?

javascript - 程序包未在 xxx :yy React Native 处运行

PHP 如果日期 >13 天前

php - Javascript 表单和对 PHP 的 Ajax 请求

jquery添加子元素属性

javascript - HTML5 详细信息-> 摘要

javascript - 处理与 WebPack 连接有关的文件顺序?

javascript - 使用 Bootstrap 3.1 在 IE9 中无法加载 CSS 压缩

javascript - 在jQuery中模拟每5秒点击一次空格键

jquery - 如何将嵌套的 div 向上移动两个 div 级别以匹配父级?