0

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].

dakab
5,97510 gold badges46 silver badges71 bronze badges
asked Mar 23, 2017 at 13:59

6 Answers 6

2

Use alert(JSON.stringify(data));.

answered Mar 23, 2017 at 14:02
Sign up to request clarification or add additional context in comments.

Comments

1

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/

answered Mar 23, 2017 at 14:02

Comments

1

Did you tried ?

var json = JSON.parse(data);
alert(json["score"]);
answered Mar 23, 2017 at 14:03

Comments

0

You should use JSON.Stringify().

JSON.Stringify()

answered Mar 23, 2017 at 14:05

Comments

0

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.

answered Mar 23, 2017 at 14:06

Comments

0

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));

answered Mar 24, 2017 at 6:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.