Reputation: 13243
I am trying to do an ajax request to get data and input it into a function parse()
. The function works when I don't use ajax, but when I use ajax, it doesn't work.
$.get(url,function(data){
parse(data);
});
The ajax response:
{"all":
{label: "All",
data: [
["11/30/2012",12],null,null,null,["01/24/2013",1442],["01/25/2013",1561]
]
}
};
However, when I call my parse function like this, it works:
var data = {"all":
{label: "All",
data: [
["11/30/2012",12],null,null,null,["01/24/2013",1442],["01/25/2013",1561]
]
}
};
parse(data);
I even tried adding data =
in front of the text in my ajax response, but the function still didn't recognize it.
Anyone know how to return an object from an ajax request?
Upvotes: 1
Views: 95
Reputation: 94499
Use the $.getJSON function, which will cause the response to be parsed as JSON.
$.getJSON(url,function(data){
parse(data);
});
or use get()
with the dataType
argument specified. The dataType
indicates the type of data expected to be returned by the server.
$.get(url,function(data){
parse(data);
}, "json");
Also consider reformatting the JSON so that it is valid (uses quotes around property names):
{
"all": {
"label": "All",
"data": [
[
"11/30/2012",
12
],
null,
null,
null,
[
"01/24/2013",
1442
],
[
"01/25/2013",
1561
]
]
}
}
Upvotes: 4