对于PHP/HTML页面,向JSON添加数据的最简单方法是什么?我应该使用PHP、JS还是jQuery?
我尝试了很多不同的方法,但我都无法使用。这些我都试过了,但都做不好。
var myObject = new Object();
JSON.stringify()
JSON.parse()
$.extend();
.push()
.concat()
我已经加载了这个JSON文件
{"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"}
]
}
我想以编程方式添加
var THISNEWCOMMENT = 'jkl;
{"thecomment": THISNEWCOMMENT}
以便JSON变量为
{"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"},
{"thecomment": "jkl"}
]
}
///////////////////回答后编辑//////////////////
这是我的index.php文件中的ajax,我用来调用php函数(在其单独的文件中):
function commentSaveAction ()
{
var mytext = $(".mycommentinput").val();
mytext = mytext.replace("'"","'");
$.ajax({
url: 'php/commentwrite.php',
data: { thePhpData: mytext },
success: function (response) {
}
});
}
这是我在deceze:的帮助下使用的PHP函数
<?php
function writeFunction ()
{
$filename = '../database/comments.txt';
$arr = json_decode(file_get_contents($filename),true);
$myData = $_GET['thePhpData'];
$arr['commentobjects'][] = array('thecomment' => $myData);
$json = json_encode($arr);
$fileWrite=fopen($filename,"w+");
fwrite($fileWrite,$json);
fclose($fileWrite);
}
writeFunction ();
?>
//////////////////////使用JS而不是PHP/////////////////////
var myJsonData;
function getCommentData ()
{
$.getJSON('database/comments.txt', function(data) {
myJsonData = data;
var count = data.commentobjects.length;
for (i=0;i<count;i++) {
$(".commentbox ul").append("<li>"+data.commentobjects[i].thecomment+"</li>");
}
});
}
function commentSaveAction ()
{
var mytext = $(".mycommentinput").val();
mytext = mytext.replace("'"","'");
myJsonData.commentobjects.push({"thecomment": mytext});
var count = myJsonData.commentobjects.length;
$(".commentbox ul").append("<li>"+myJsonData.commentobjects[count-1].thecomment+"</li>");
}
无论使用哪种语言,都必须将JSON字符串解析为对象/数组,对其进行修改,然后将其编码回JSON字符串。不要尝试对JSON字符串进行任何直接的字符串操作。PHP示例:
$arr = json_decode($json, true);
$arr['commentobjects'][] = array('thecomment' => 'jkl');
$json = json_encode($arr);
是否在Javascript、PHP或其他地方执行此操作取决于何时/为什么/在哪里需要执行此操作;如果不了解更多关于用例的信息,这是不可能的。
尝试使用json_encode
和json_decode
PHP函数。
//work on arrays in php
$arr = array('sth1', 'sth2');
//here you have json
$jsonStr = json_encode($arr);
//array again
$arrAgain = json_decode($jsonStr);
$arrAgain[] = 'sth3';
//json again
$jsonAgain = json_encode($arrAgain)
只需在javascript:中执行即可
var x = {"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"}
]
};
x.commentobjects.push({"thecomment": "jkl"});
var THISNEWCOMMENT = 'jkl',
myObj = JSON.parse(rawJson),
newComment = {"thecomment": THISNEWCOMMENT};
myObj.commentobjects.push(newComment);
var serialized = JSON.stringify(myObj);
//send the updated JSON to your controller
解析对象,访问其中的commentobject
列表,推送列表中的新注释,然后再次序列化更新后的对象。