Reputation: 7218
I was playing with $.getJSON in the following way to receive an alert but without luck.
Here is the code,
<script type="text/javascript">
$(document).ready(function() {
var url = "ticker.js?callback=?";
$.getJSON(url, function(data) {
alert(data.price);
});
});
</script>
And the ticker.js file has only the following line
{ticket:'IBM',price:14.57}
It is supposed to get an alert "14.57" but I am not getting the alert.
If you would like to see it in action you may try the link, http://nazmulweb.com/site5/demo/jsonPtest/
Upvotes: 4
Views: 15804
Reputation: 630349
If it's a local file, you should remove the ?callback=?
part, like this:
var url = "ticker.js";
$.getJSON(url, function(data) {
alert(data.price);
});
If you look at the $.getJSON()
docs, there's this:
If the URL includes the string
"callback=?"
in the URL, the request is treated as JSONP instead. See the discussion of thejsonp
data type in $.ajax() for more details.
With JSONP it's expecting randomFunctioName({ticket:'IBM',price:14.57});
in the response, not just the JSON, but a function call...this is how JSONP works cross-domain, by being a <script>
tag. Since you just want JSON and to process it from a local source, remove the callback=?
piece.
Edit: I completely missed the second issue, your current JSON isn't valid and will fail jQuery's checks added in 1.4. It needs to be this:
{ "ticket": "IBM", "price": 14.57 }
You can test your JSON for validity here: http://www.jsonlint.com/
Upvotes: 6