Adding Data Dynamically From One Json Object To Another
Solution 1:
You're pretty much going to need a server-side process if you want to save your changes.
You can load the JSON via 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
}
});
To add to the deserialized object, you just modify it in memory:
friends.people.push({
id: String(friends.people.length + 1),
name: "John",
img: "img/john.jpg"
});
Of course, those values will probably come from input fields or something, e.g.:
functionaddPerson() {
friends.people.push({
id: String(friends.people.length + 1),
name: $("#nameField").val(),
img: $("#imgField").val()
});
}
Now you have an in-memory copy of your data. To store it somewhere, you have to have a server-side process you can post it to. You'd probably serialize it before posting, e.g., via JSON.stringify
or similar. If your browser doesn't have JSON.stringify
natively (most modern ones do, some older ones don't), you can use Crockford's.
Or if this is just for your own use, you could display the stringified result in a text field and the use copy-and-paste to paste it into friends.json
in a text editor.
Here's a complete example, which shows the JSON in a text area: Live copy | source
<!DOCTYPE html><html><head><metacharset=utf-8 /><title>Test Page</title><style>body {
font-family: sans-serif;
}
</style></head><body><label>Name:
<inputtype="text"id="nameField"></label><br><label>Img:
<inputtype="text"id="imgField"></label><br><inputtype="button"id="btnAdd"value="Add"disabled><inputtype="button"id="btnShow"value="Show JSON"disabled><br><divid="msg"> </div><hr><textareaid="showField"rows="10"cols="60"></textarea><scriptsrc="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 (typeofJSON === "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 erroralert("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" functionfunctionaddPerson(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>
Post a Comment for "Adding Data Dynamically From One Json Object To Another"