开发者

parse json object from server side

IN my web service,I return one json object in the method:

{name:'xx'}

I use the ajax to send the request,then parse them using the 'eval'

onComplete:function(req){
  var data=eval(req.responseText);
  //do something according data
}

However,I can not get the 'data'.

When I retrun the following string:

[{name:'xx'}]

It worked,and I get the 'data' as an array.

Through google,I know that it is caused by the '{' in the return string.

So I wonder if there is no way to retrun a开发者_如何学Python json object ?


Use JSON.parse or jquery's $.parseJSON - if you use jquery - instead of eval.
Also, if you do use jquery, you can take advantage of the built-in ajax method that automaticly retrieves and parses the response as a json object : $.getJson.

If you still don't want to modify your "logic", you can try to eval your response with added brackets : var data = eval('(' + req.responseText + ')');


Have a read of this blog post on JSON hijacking. The author explains the issue your running into

You might have seen code like the following when related to JSON:

eval('('+JSON_DATA+')');

Notice the beginning and ending parenthesis, this is to force JavaScript to execute the data as an object not a block statement mentioned above. If JavaScript did attempt to execute JSON data without the parenthesis and the JSON data did in fact begin with “{” then a syntax error would occur because the block statement would be invalid.

...more info on why...

Rather than adding () around your JSON response, you should be using JSON.parse or $.parseJSON like gion_13 has said. Eval isn't the way to go.

Also, like quentin said in the comments, you need to change the JSON you're returning as it's invalid. You need to quote your key as well as your value.


It worked,and I get the 'data' as an array.

That's what it's supposed to do. [] is the syntax for declaring an array. If you want the inner object, then just return {name: 'XX'}.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜