Jquery getJSON not firing callback with valid json response
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!
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.
精彩评论