如何使用jQuery添加/附加到外部JSON文件

cDe*_*eke 2 javascript jquery json

我有一个json文件,我想构建一个表单,该表单允许我在文件中添加/编辑元素。是否有一个jQuery函数/方法,使我能够在外部json文件中发布和追加元素?

不知道这是否有帮助,但是当前的json结构如下:

 [ { "cast" : "",
    "director" : "",
    "genre" : "",
    "id" : false,
    "nrVotes" : 0,
    "plot" : "",
    "rating" : 0,
    "runtime" : 0,
    "title" : "",
    "year" : false
  },
  { "cast" : "Tim Robbins, Morgan Freeman, Bob Gunton, ",
    "director" : "Frank Darabont",
    "genre" : "Crime Drama ",
    "id" : "0111161",
    "nrVotes" : 968510,
    "plot" : "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
    "rating" : 9.3000000000000007,
    "runtime" : 142,
    "title" : "The Shawshank Redemption",
    "year" : "1994"
  }]
Run Code Online (Sandbox Code Playgroud)

非常感谢您!!(:

Jas*_*han 5

如果您使用的是jQuery的getJSONparseJSON(),则可以使用一个JavaScript对象。例如:

$.getJSON( "/test.json", function( data ) {
  // now data is JSON converted to an object / array for you to use.
  alert( data[1].cast ) // Tim Robbins, Morgan Freeman, Bob Gunton

  var newMovie = {cast:'Jack Nicholson', director:...} // a new movie object

  // add a new movie to the set
  data.push(newMovie);      
});
Run Code Online (Sandbox Code Playgroud)

您现在要做的就是保存文件。您可以使用jQuery.post()将文件发送回服务器以为您保存。

更新:发布示例

//inside getJSON()

var newData = JSON.stringify(data);
jQuery.post('http://example.com/saveJson.php', {
    newData: newData
}, function(response){
    // response could contain the url of the newly saved file
})
Run Code Online (Sandbox Code Playgroud)

在您的服务器上,使用PHP的示例

$updatedData = $_POST['newData'];
// please validate the data you are expecting for security
file_put_contents('path/to/thefile.json', $updatedData);
//return the url to the saved file
Run Code Online (Sandbox Code Playgroud)