Tôi tin rằng anh ấy yêu cầu viết json mới vào một thư mục. Bạn sẽ cần một số Javascript và PHP. Vì vậy, để heo con quay trở lại các câu trả lời khác:
script.js
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
var myString = 'newData='+JSON.stringify(yourObject); //converts json to string and prepends the POST variable name
$.ajax({
type: "POST",
url: "buildJson.php", //the name and location of your php file
data: myString, //add the converted json string to a document.
success: function() {alert('sucess');} //just to make sure it got to this point.
});
return false; //prevents the page from reloading. this helps if you want to bind this whole process to a click event.
buildJson.php
<?php
$file = "data.json"; //name and location of json file. if the file doesn't exist, it will be created with this name
$fh = fopen($file, 'a'); //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.
$new_data = $_POST["newData"]; //put POST data from ajax request in a variable
fwrite($fh, $new_data); //write the data with fwrite
fclose($fh); //close the dile
?>
@guillaumealgis, bạn có thể giải thích cuộn của bạn trở lại để chỉnh sửa của tôi? Nếu bạn chạy đối tượng thông qua [JSONLint] (http://jsonlint.com/), nó được gắn cờ là không hợp lệ (các phím bên trái cần phải được trích dẫn kép). Tôi không cho rằng bạn sai, tôi muốn tìm hiểu lý do tại sao bạn tin rằng đó là JSON hợp lệ vì nó có thể là thứ mà tôi không hiểu. Nếu bạn chạy phiên bản của tôi thông qua trình xác nhận hợp lệ, nó sẽ trở lại dưới dạng JSON hợp lệ. – delliottg
@delliottg Không sử dụng trình xác thực JSON để xác thực JavaScript. Vui lòng đọc lại câu trả lời của tôi. –
@delliottg Tôi không nói đó là JSON hợp lệ. Điểm của câu trả lời này là phân biệt JSON một đối tượng JS. Hãy thử chạy mã dystroy trong một trình thông dịch JS và bạn sẽ thấy rằng nó chạy tốt. –