javascript 如何使用 jQuery 添加/附加到外部 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19473885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Add/Append to external JSON file using jQuery
提问by cDemeke
I've got a json file that I would like to build a form that will allow me to add / edit elements in the file. Is there a jQuery function/ method that will allow me to be able to post and append elements in the external json file?
我有一个 json 文件,我想构建一个表单,允许我在文件中添加/编辑元素。是否有一个 jQuery 函数/方法可以让我能够在外部 json 文件中发布和附加元素?
Not sure if this will help but the current json structure is as follow:
不确定这是否有帮助,但当前的 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"
}]
Huge thank you in advance!! (:
非常感谢您提前!(:
回答by Jason J. Nathan
if you are using jQuery's getJSONor parseJSON(), you have a javascript object you can manipulate. for example:
如果您使用 jQuery 的getJSON或parseJSON(),则您有一个可以操作的 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:'Hyman Nicholson', director:...} // a new movie object
// add a new movie to the set
data.push(newMovie);
});
All you have to do now is save the file. You can use jQuery.post() to send the file back to the server to save it for you.
您现在要做的就是保存文件。您可以使用 jQuery.post() 将文件发送回服务器为您保存。
Update: Posting an example
更新:发布一个例子
//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
})
On your server, example using PHP
在您的服务器上,使用 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
回答by sudheer suri
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
<?php
$str = file_get_contents('data.json');//get contents of your json file and store it in a string
$arr = json_decode($str, true);//decode it
$arrne['name'] = "sadaadad";
$arrne['password'] = "sadaadad";
$arrne['nickname'] = "sadaadad";
array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
$str = json_encode($arr);
//now send evrything to ur data.json file using folowing code
if (json_decode($str) != null)
{
$file = fopen('data.json','w');
fwrite($file, $str);
fclose($file);
}
else
{
// invalid JSON, handle the error
}
?>
<form method=>
</body>
data.json
数据.json
{
"employees":[
{
"email":"11BD1A05G9",
"password":"INTRODUCTION TO ANALYTICS",
"nickname":4
},
{
"email":"Betty",
"password":"Layers",
"nickname":4
},
{
"email":"Carl",
"password":"Louis",
"nickname":4
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
}
]
}