Harshad Hirapara Harshad Hirapara - 4 months ago 7
Ajax Question

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

My specific situation: I have an array defined as shown below:

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...


and I need to turn this into a string to pass to $.ajax() like this:

$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'countries':['ga','cd']}",
...

Answer

You can use JSON.stringify(countries);

var c = {
   countries: countries
}
$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: JSON.stringify(c),
    contentType: "application/json"
...

Note that you will want to specify contentType; otherwise, URI-encoding is assumed.

Comments