I have this code:
GameManager.prototype.initGame = function () {
var api = 'my_url';
$.ajax({
url : api,
type : 'POST',
data: "",
dataType : 'json',
success : function(data) {
alert(data);
}
});
};
I see in the Firebug console the JSON:
[{"data":{"score":500,"token":"2896c5380bf3e3e29467258c7fe885fe"}}]
But the alert(data) shows me [object Object].
6 Answers 6
Use alert(JSON.stringify(data));.
Comments
The object will already have been parsed when using:
dataType : 'json'
This is what the doc says:
"json": Evaluates the response as JSON and returns a JavaScript objec
You can read more about the dataType parameter here http://api.jquery.com/jquery.ajax/
Comments
Did you tried ?
var json = JSON.parse(data);
alert(json["score"]);
Comments
You should use JSON.Stringify().
Comments
console.log is for strings (link). I think you are doing everything ok, you just need to get certain properties from your object, eg. data.score if you want to output them using console.log, because I assume you will be working with data ir JSON format, and not in stringified version.
Comments
Try JSON.stringify() method to display the data of JSON object in alert. It will convert the JSON Object into JSON String.
DEMO
var jsonObj = [{
"data": {
"score": 500,
"token": "2896c5380bf3e3e29467258c7fe885fe"
}
}];
alert(JSON.stringify(jsonObj));