I will be passing a json string to a servlet via an ajax request :
function add() {
$.ajax({
url: "pathToServlet" ,
dataType: "text",
data: ({
name : 'myJsonString'
}),
success: function(data) {
alert('returned!!');
});
}
To build up this json string I have a listener which when fired appends a new piece of json to string :
var json = "";
json += "{ new json ..... }"
Is this the correct way to build up the jSon String ? Should I be using jQuery methods to create a json object(if they exist) and add elements to it and then convert the json object to a string instead of creating the json string myself ?
What I would recommend doing is building up an object, and then when you’re ready to send it to the server, serialize the object via
JSON.stringify.So for instance, you might have an object called
data:…to which you might periodically add properties:
Or perhaps
datais an array:…to which you add things:
Then, when you’re ready to send it:
Because you’re passing an object into
ajax, you don’t have to worry about URL-encoding the JSON string; jQuery will do it for you.JSON.stringifyis defined as part of ECMAScript5 and suppoted natively by many browsers, but of course many of us have to support outdated versions of browsers. In those cases, you can get a “JSON shim” to addJSON.stringifyto an environment that doesn’t have it. One of those is available from the originator of JSON, Douglas Crockford, on his github page.