変更を保存する場合は、サーバー側のプロセスが必要になります。
JSONは次の方法で読み込むことができますajax
:
$.ajax({
url: "/path/to/friends.json",
dataType: "json",
success: function(data) {
// Here, `data` will be the object resulting from deserializing the JSON
// Store `data` somewhere useful, perhaps you might have a `friends`
// variable declared somewhere; if so:
friends = data;
},
error: function() {
// Handle the error
}
});
デシリアライズされたオブジェクトに追加するには、メモリ内でオブジェクトを変更するだけです。
friends.people.push({
id: String(friends.people.length + 1),
name: "John",
img: "img/john.jpg"
});
もちろん、これらの値はおそらく入力フィールドなどから取得されます。例:
function addPerson() {
friends.people.push({
id: String(friends.people.length + 1),
name: $("#nameField").val(),
img: $("#imgField").val()
});
}
これで、データのメモリ内コピーができました。どこかに保存するには、投稿できるサーバー側のプロセスが必要です。おそらく、投稿する前に、たとえば経由JSON.stringify
などでシリアル化するでしょう。お使いのブラウザにネイティブがない場合JSON.stringify
(ほとんどの最新のものにはありますが、一部の古いものにはありません)、Crockfordのものを使用できます。
または、これが自分で使用する場合は、文字列化された結果をテキストフィールドに表示し、コピーアンドペーストを使用しfriends.json
てテキストエディタに貼り付けることができます。
完全な例を次に示します。これは、テキスト領域にJSONを表示します。ソース
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test Page</title>
<style>
body {
font-family: sans-serif;
}
</style>
</head>
<body>
<label>Name:
<input type="text" id="nameField">
</label>
<br><label>Img:
<input type="text" id="imgField">
</label>
<br><input type="button" id="btnAdd" value="Add" disabled>
<input type="button" id="btnShow" value="Show JSON" disabled>
<br><div id="msg"> </div>
<hr>
<textarea id="showField" rows="10" cols="60"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
// Note that all of our script tags are at the end of the
// document. This lets the page load as quickly as possible
// and means we don't have to worry about whether the elements
// have been created yet (they have, because the scripts are
// below them).
// Put all of our code inside a function so we don't
// create globals
(function($) {
if (typeof JSON === "undefined") {
// Load Crockford's json2.js
// NOTE: You'd want to use your own copy, not a hotlink
// to his github like this.
var scr = document.createElement('script');
scr.src = "https://raw.github.com/douglascrockford/JSON-js/master/json2.js";
document.documentElement.appendChild(scr);
}
var friends; // Where our deserialized friends.json will go
// Focus the first field
$("#nameField").focus();
// Load the JSON
$.ajax({
url: "http://jsbin.com/ojexuz",
dataType: "json",
success: function(data) {
// Here, `data` will be the object resulting from deserializing the JSON
// Store `data` somewhere useful, perhaps you might have a `friends`
// variable declared somewhere; if so:
friends = data;
// Enable our buttons now that we have data
$("input[type='button']").prop("disabled", "");
},
error: function() {
// Handle the error
alert("Error loading friends.json");
}
});
// Handle clicks on the "Add" button
$("#btnAdd").click(function() {
var nameField = $("#nameField"),
imgField = $("#imgField"),
name = $.trim(nameField.val()),
img = $.trim(imgField.val());
if (!name || !img) {
alert("Please supply both name and image");
return;
}
addPerson(name, img);
$("#msg").text("Added '" + name + "'");
nameField.focus();
});
// An "add this person" function
function addPerson(name, img) {
friends.people.push({
id: String(friends.people.length + 1),
name: name,
img: img
});
}
// Handle clicks on the "Show" button
$("#btnShow").click(function() {
$("#showField").val(JSON.stringify(friends));
});
})(jQuery);
</script>
</body>
</html>