javascript - 如何使用php将动态添加的数据保存并显示到json?

标签 javascript php jquery html json

我有一个简单的 block ,用户可以在其中单击添加多个按钮,现在我使用push将这些按钮添加到json,现在我想使用PHP将添加的按钮保存到json文件。

根据 Arleigh Hix 进行更新

我的 json 看起来像这样

    var movies = [{
      "title": "travel",
      "left": 201,
      "top": 209,
      "movieid": "10",
      "movie_url": "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4",
      "buttons": [{
        "left": 81,
        "top": 51,
        "start_time": 1,
        "end_time": 2,
        "buttonid": "10_1",
        "btn_url": "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
      }]
    },
    {
      "title": "ecommerce",
      "movieid": "20",
      "movie_url": "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4",
      "buttons": [{
        "left": 0,
        "top": 0,
        "start_time": 1,
        "end_time": 2,
        "width": '200',
        "height": '60',
        "buttonid": "20_1",
      }]
    }
  ]

这是用于添加按钮的 HTML block

 <div id="layers-container" style="width: 375px;">
      <div class="layer"></div>
 </div>

这里是js

      $("#add-button").on("click", function(index){

                        var layer = $("<div class='layer'><div class='content-layer'></div></div");

                        $("#layers-container").append(layer);
                        var clickarea = $("<div class='clickarea'></div>");
                        $(".caption-content").append(clickarea);                       
                        $('.content-layer').each(function(index){
                                var value = index + 1;     
                                $(this).attr('id','contentLayerID' + value);
                        });

                        $('.clickarea').each(function(index){
                                var value = index + 1;    
                                $(this).attr('id','clikckAreaID' + value);
                                for (var a = 0; a < movies.length; a++) {
                                        for (var j = 0; j <movies[a].buttons.length; j++) {
                                                movies[j].buttons.push({
                                                        left: 20,
                                                        top: 20,
                                                        buttonid:clickarea.attr('id', 'clickAreaID', value)
                                                });

                                  };

                                }

                                    $.post('save_to_json.php', {movies:movies}, function(data, textStatus){
                                        console.log(textStatus, data);
                                    });
                        });

   })

这是我启动的 php 文件:save_to_json.php

   <?php
if(isset($_POST['movies'])){
    $movies = json_decode($_POST['movies']);
    // do whatever checks you need on $movies to verify valid data

    $success = file_put_contents("data.json", json_encode($movies));
    if($success === false){
        echo "Failed to write data to file";
        die();
    }else{
        echo "$success bytes were written to the file";
        die();
    }
}

$data=file_get_contents("data.json");
$result=json_decode($data);
?>

我收到此错误

Uncaught TypeError: Illegal invocation at e (jquery.min.js:4) at Vc (jquery.min.js:4)

说实话,我是 PHP 新手,我不知道下一步该做什么。

我需要做什么才能得到我想要的东西?

最佳答案

.each() 函数之后,将更新后的 json 发送到 php 文件:https://api.jquery.com/jquery.post/

$("#add-button").on("click", function(index){
    ...

        $('.clickarea').each(function (index) {
            ...        
        });

        let jsonString = JSON.stringify({movies:movies});
        $.post('myPhpFileURL', jsonString, function(data, textStatus){
            console.log(textStatus, data);
        });

    });

在 php 文件中检查并检索 $_POST https://www.php.net/manual/en/reserved.variables.post.php 中的数据,

然后保存数据https://www.php.net/manual/en/function.file-put-contents.php

<?php
if(isset($_POST['movies'])){
    $movies = json_decode($_POST['movies']);
    // do whatever checks you need on $movies to verify valid data

    $success = file_put_contents("file.json", json_encode($movies));
    if($success === false){
        echo "Failed to write data to file";
        die();
    }else{
        echo "$success bytes were written to the file";
        die();
    }
}

$data=file_get_contents("file.json");
$result=json_decode($data);
?>

关于javascript - 如何使用php将动态添加的数据保存并显示到json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56743743/

相关文章:

jquery - 在 jquery 的数组中检查 radio

javascript - 将 POST 数据作为隐藏的输入名称值数组发送

javascript - Firebase signInwithRedirect() 总是转到本地主机而不是我的应用程序

javascript - IE8。为什么 typeof 在子窗口中表现不同?

php:如何从数字索引中获取关联数组键?

jQuery:检查下一个元素,如果没有隐藏

JavaScript 与 ASP.NET 确认

php - 如何使用 fputcsv 将单个值放入单列中

php-fpm.sock 在 CentOS 7 上缺少 : php7. 2

javascript - 是否有一个集合映射 jquery 函数,其中 end 方法适用于基本查询