[英]How to parse JSON with JavaScript from Ajax request
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: 我在Firebug控制台中看到JSON:
[{"data":{"score":500,"token":"2896c5380bf3e3e29467258c7fe885fe"}}]
But the alert(data)
shows me [object Object]
. 但是alert(data)
向我显示[object Object]
。
Use alert(JSON.stringify(data));
使用alert(JSON.stringify(data));
. 。
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 “ json”:将响应评估为JSON并返回JavaScript objec
You can read more about the dataType parameter here http://api.jquery.com/jquery.ajax/ 您可以在http://api.jquery.com/jquery.ajax/上阅读有关dataType参数的更多信息。
Did you tried ? 你试过了吗?
var json = JSON.parse(data);
alert(json["score"]);
You should use JSON.Stringify(). 您应该使用JSON.Stringify()。
console.log
is for strings ( link ). console.log
用于字符串( 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. data.score
如果您想使用console.log
输出它们,因为我假设您将使用ir JSON格式的数据,而不是stringified
版本。
Try JSON.stringify() method to display the data of JSON
object in alert
. 尝试使用JSON.stringify()方法在alert
显示JSON
对象的数据。 It will convert the JSON
Object into JSON
String. 它将JSON
对象转换为JSON
字符串。
DEMO 演示
var jsonObj = [{ "data": { "score": 500, "token": "2896c5380bf3e3e29467258c7fe885fe" } }]; alert(JSON.stringify(jsonObj));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.