[英]Writing an object to an existing json file and wrapping the contents with '[ ]'
[英]Writing a JSON object to an existing .json file
編輯:我的錯誤檢查顯示PHP正在執行,但當我檢查我的.json文件時,它仍然與以前一樣。
我提前道歉,因為之前已經問過這個問題,但是我花了好幾個小時嘗試不同的東西而且都沒有。 希望這可能會幫助處於類似情況的人。 我正在嘗試從用戶輸入向我現有的json對象追加一個新條目,並將更新的json對象寫回文件。 最后一部分是給我帶來麻煩的。
在這里,我使用ajax將我的json對象發送到php文件
$.getJSON("http://existing.json", function(data){
//append new entry to previous json array
data['posts'].push(objectt);
//confirming that new object is correct
console.dir(data);
//Sending json object to .php file so it can write to .json file
$.ajax({
type : "POST",
url : "json.php",
//data : data, this was changed to
data : {json:data}, //by the suggestion of suggested by madalin ivascu
dataType: 'json'
});
上面的代碼塊執行,控制台中不顯示任何錯誤。 這是我的json.php文件。 在下一個代碼塊執行后,我的.json文件沒有新條目。
$json = $_POST['json'];
if ($_POST['json'])
{
$file = fopen('simple.json','w+');
fwrite($file, $json);
fclose($file);
echo: "File was updated";
}
else
{
// user has posted invalid JSON, handle the error
print "Error json was null";
}
更改data : {json:data},
從php返回一些東西
$json = $_POST['json'];
if (json_decode($json) != null)
{
$file = fopen('simple.json','w+');
fwrite($file, $json);
fclose($file);
echo "File updated";
}
else
{
// user has posted invalid JSON, handle the error
print "Error json was null";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.