如何获得PHP脚本删除JSON文件中的对象

How to get PHP script to delete an object in JSON file?

本文关键字:文件 对象 JSON 删除 何获得 PHP 脚本      更新时间:2023-09-26

所以我有一个HTML文件,它动态地填充了来自JSON文件的信息,带有ajax _POST请求。

我所要做的就是抓取json(只是一个简单的对象数组),通过ajax传递的索引号剥离出适当的一个,然后将json重新编码回同一个文件。没有错误,但什么也没发生。

谢谢!

这是我的ajax:

$(document).ajaxComplete(function(event, xhr, settings) {
        var json = "data/comments.json";
        $('.delete').click(function(index) {
            var deleteIndex = $(this).parent().attr('id');
            var deleteIndex = parseInt(deleteIndex);
            $.ajax({
                type: 'POST',
                url: 'data/save.php', // the url where we want to POST
                data: deleteIndex,
                success: function(){ 
                                        location.reload();
                                    },
                error: function(){    
                                        alert('Fail!');
                                    }
                });
        });
    });

下面是我的PHP:

<?php
$data => $_POST['deleteIndex'];
$file = file_get_contents('comments.json');
$json[] = json_decode($file, true); //return an array
foreach($json as $key => $value) {
   if($value == $data) {
    unset($json[$data]);
    file_put_contents('comments.json', json_encode($json, JSON_PRETTY_PRINT));
   }
}
?>

您没有设置发送给服务器的值的名称。请求中的data键应该是一个{key:val}对象(或一个url格式的字符串)。

    $(document).ajaxComplete(function(event, xhr, settings) {
    var json = "data/comments.json";
    $('.delete').click(function(index) {
        var deleteIndex = $(this).parent().attr('id');
        var deleteIndex = parseInt(deleteIndex);
        $.ajax({
            type: 'POST',
            url: 'data/save.php', // the url where we want to POST
            data: {'deleteIndex': deleteIndex},
            success: function(){ 
                location.reload();
            },
            error: function(){    
                alert('Fail!');
            }
        });
    });
});

在你的PHP代码中,我认为这会更好:

$data = $_POST['deleteIndex'];
$file = file_get_contents('comments.json');
$json = json_decode($file, true); //return an array
unset($json[$data]); // I guess you want to delete the value by key
file_put_contents('comments.json', json_encode($json));