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

时间:2019-06-24 20:48:32

标签: javascript php jquery html json

我有一个简单的块,用户可以在其中单击添加多个按钮,现在我正在使用推式将这些按钮添加到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块

 <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);
?>

我收到此错误

  

未捕获的TypeError:非法调用       在e(jquery.min.js:4)       在Vc(jquery.min.js:4)

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

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

2 个答案:

答案 0 :(得分:1)

.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);
?>

答案 1 :(得分:0)

请详细描述您要做什么,以便社区可以为您提供更好的帮助。

要将JSON字符串写入PHP文件中,您只需执行以下操作:

<?php
file_put_contents("file.json", $_POST['movies']);

假设您首先使用Javascript对数组进行JSON编码,然后使用HTML表单将JSON字符串发布到PHP脚本中。