Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send a JavaScript array as a JSON value?

How can I send a JavaScript array as a JSON variable in my AJAX request?

like image 604
thedp Avatar asked May 11 '10 21:05

thedp


2 Answers

This requires you to serialize the javascript array into a string, something that can easily be done using the JSON object.

var myArray = [1, 2, 3];
var myJson = JSON.stringify(myArray); // "[1,2,3]"
....
xhr.send({
    data:{
        param: myJson
    }
});

As the JSON object is not present in older browsers you should include Douglas Crockfords json2 library

If you already rely on some library that includes methods for encoding/serializing then you can use this instead. E.g. ExtJs has Ext.encode

like image 197
Sean Kinsey Avatar answered Oct 05 '22 17:10

Sean Kinsey


If you're not using a javascript library (jQuery, prototype.js, etc) that will do this for you, you can always use the example code from json.org

like image 25
timdev Avatar answered Oct 05 '22 17:10

timdev