Vous aurez à peu près besoin d'un processus côté serveur si vous souhaitez enregistrer vos modifications.
Vous pouvez charger le 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
}
});
Pour ajouter à l'objet désérialisé, vous modifiez simplement en mémoire:
friends.people.push({
id: String(friends.people.length + 1),
name: "John",
img: "img/john.jpg"
});
Bien sûr, ces valeurs proviennent probablement de l'entrée champs ou quelque chose, par exemple:
function addPerson() {
friends.people.push({
id: String(friends.people.length + 1),
name: $("#nameField").val(),
img: $("#imgField").val()
});
}
Maintenant vous avez une copie en mémoire de y nos données Pour stocker quelque part, vous devez avoir un processus côté serveur, vous pouvez le poster. Vous devrez probablement le sérialiser avant de le publier, par exemple via JSON.stringify
ou similaire. Si votre navigateur ne dispose pas de JSON.stringify
nativement (la plupart des modernes le font, certains plus anciens ne le font pas), vous pouvez utiliser Crockford's.
Ou si cela est juste pour votre usage personnel, vous pouvez afficher le résultat stringifié dans un champ de texte et l'utilisation copier-coller pour le coller dans friends.json
dans un éditeur de texte.
Voici un exemple complet, qui montre le JSON dans une zone de texte: Live copy | source
<!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>
Ce JSON est invalide de plusieurs façons. Les clés doivent être entre guillemets, comme toutes les autres chaînes (telles que 'Friends' et'/friends.json'). Voir http://json.org et jsonlint.com. –
Créez simplement des objets javascript à partir de vos chaînes JSON en utilisant JSON.parse et effectuez des opérations javascript basiques sur vos objets. –
Je suis assez nouveau à jQuery et json, donc ne pas avoir beaucoup de connaissances à leur sujet. Je n'arrive pas à penser à quoi que ce soit qui explique pourquoi j'ai posté cette question. C'est peut-être un peu bête mais toute aide sera grandement appréciée. –