我正在尝试将数据添加到 *.JSON 文件,该文件仅包含以下文本:{}。 Ajax 返回“成功”,但文件仍保持原来状态。我还注意到,如果 JSON 文件为空,则什么也不会发生。请帮助我找到解决方案。我不明白问题出在哪里。也许,您知道问题的其他原因是什么。谢谢。
ajax的代码:
$.ajax({
type: "POST",
url: "data/test.json",
data: JSON.stringify({ "userName": "1", "password" : "1" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert("success");},
fail: function(errMsg) {alert("fail");
}
});
最佳答案
最好的解决方案是安装 denver 并在服务器端使用 PHP 代码。
这是js文件中的代码。
deleteNewsItem: function(newsId, callback, scope) {
var dataPath = this.dataPath;
$.getJSON(dataPath + '/delete-news.php?id='+newsId, function(rawHeadlines) {
var headlines = [];
$.each(rawHeadlines, function(index, rawHeadline) {
headlines.push(rawHeadline.id);
}
});
if (callback) {
callback.call(scope, headlines);
}
};
这是“delete_news.php”文件中的代码。
<?php
$deleteId = isset($_GET['id'])?$_GET['id']:false;
if ($deleteId){
$content = file_get_contents('delete-news.json');
$json = json_decode($content);
$newData = array();
foreach($json as $key=>$id){
$newData []= (array)$id;
}
$newData []= array("id"=>(int)$deleteId);
$fill_view = json_encode($newData);
file_put_contents('delete-news.json', ($fill_view));
echo $fill_view;
} else {
echo json_encode(array());
}
exit();
?>
关于javascript - Ajax POST 返回成功,但不更新 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29127878/