3

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 json object ?

3
  • 1
    possible duplicate of Why does JavaScript's eval need parentheses to eval JSON data? Commented Jul 27, 2011 at 11:22
  • 1
    Also, that isn't JSON. Commented Jul 27, 2011 at 11:22
  • 1
    Also, eval is a slow, hard to debug and dangerous way to parse JSON (especially if it is broken JSON). Use a proper parser. jQuery (which you appear to be using) has one built in. IIRC it will trigger automatically if you return the JSON with the correct content type HTTP header (which is application/json). Commented Jul 27, 2011 at 11:23

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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'}.

Comments

Your Answer

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.