0

I've got a server that's returning valid json objects (as validated by jsonlint.com) that look like this:

"{\"encryption\": {\"key\": \"gKV0oPJwC5CBQxmn\"}}"

My html file looks like this:

<html>
  <head>
    <title>Testing Jsonp</title>
    <script type="text/javascript" src='jquery-1.4.4.js'></script>
    <script type="text/javascript" src='app.js'></script>
  </head>
  <body>
    <input type='text' value='thing' id='target' />
    <a href='' class='init'>Click</a>
  </body>
</html>

app.js looks like this:

$(document).ready(function(){
  $('.init').click(function(event){
    $.getJSON("http://localhost:37280/sites/1/encode?callback=?", { key: $("#target").attr('value') }, function(data){
      alert('Success!');
    });
    event.preventDefault();
  });
});

When I click on "Click" the Chrome network console indicates that the request is sent, my server logs confirms that the request is received and chrome indicates it receives the above json string. But then nothing happens. I don't get the alert which leads me to believe my callback isn't executing. Any help would be greatly appreciated!

5
  • Is the response actually returning the quotes around the JSON object? They should not be there. Commented Mar 24, 2011 at 19:55
  • Add an error handler and see what it says. Commented Mar 24, 2011 at 19:56
  • I've had the server return the string both ways, it does not appear to make a difference in the execution of the callback. Commented Mar 24, 2011 at 19:57
  • I noticed when I set the server to return {"encryption": {"key": "gKV0oPJwC5CBQxmn"}} instead of "{"encryption": {"key": "gKV0oPJwC5CBQxmn"}}" the Chrome console throws this error: "Uncaught SyntaxError: Unexpected token :" Commented Mar 24, 2011 at 20:16
  • Also added an error handler which doesn't produce any output. Commented Mar 24, 2011 at 20:22

1 Answer 1

3

That is not valid JSON. JSONLint seems to (newly?) claim that a raw string is valid JSON. This is not true. The JSON root must always be an array or object. RFC 4627 says:

"A JSON text is a serialized object or array."

Also, you're using JSONP, so you need to include the callback, which you haven't shown in your response.

So if the actual URL is http://localhost:37280/sites/1/encode?callback=jsonp1234

where jsonp1234 is a function name chosen by jQuery, the response must be:

jsonp1234({"encryption": {"key": "gKV0oPJwC5CBQxmn"}});

Note that this, like all JSONP, is actually JavaScript. This is how it can be cross-domain.

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

1 Comment

Not including the callback was my mistake. Thanks so much!

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.