[英]Ajax POST returns success, but doesn't update the JSON file
我正在嘗試將數據添加到* .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();
?>
單獨使用jquery無法保存json文件。 您必須實現服務器端代碼才能使其正常工作。
您的代碼中有一些錯誤,首先沒有諸如failure之類的東西,而是error或fail。 試試這個,告訴我是否有幫助。 我認為如果要獲取或存儲需要服務器端的信息,則無法使用javascript / jquery將數據保存到文件中(如果出於安全原因),如果您只想存儲少量數據,則可以使用Cookie或localStorage(“ Key”,“ Value As Json”);
您可以像這樣將數據保存到localStorage中:
$.get("data/test.json", null, function (data) {
localStorage.setItem("data", JSON.stringify(data));
});
但不幸的是,正如我之前所說,您無法使用javascript / jquery保存到文件,請嘗試使用localStorage進行臨時存儲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.