javascript - 如何获取 PHP 脚本来删除 JSON 文件中的对象?

标签 javascript php jquery json ajax

所以我有一个 HTML 文件,它通过 ajax _POST 请求动态填充 JSON 文件中的信息。

我想做的就是获取 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));

关于javascript - 如何获取 PHP 脚本来删除 JSON 文件中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117034/

相关文章:

javascript - 尝试将 Go Pro GYRO 数据转换为 Three.js 中的旋转

javascript - 如何从回调函数中查询引起ajax调用的表单?

javascript - 更好的 JS if 条件编程风格

javascript - 使用 React 切换 Font Awesome 5 图标

php - jQuery简单的自动添加项目表单

php - 当我们在php中从数据库中获取大量数据时显示空白数据?

javascript - datatables不加载json(带有对象的数组)

php - Dropbox API 400 错误 : “4xx Error (4xx) We can' t find the page you're looking for.”

javascript - 内容扩展到 div 之外但没有滚动条

jQuery Select2 样式更新更改 CSS 类样式