$ .getJSON to get JSONP data

I played with $ .getJSON as follows to get a warning, but no 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 the warning "14.57", but I do not get the warning.

If you want to see it in action, you can try the link, http://nazmulweb.com/site5/demo/jsonPtest/

+4
source share
1 answer

If this is a local file, you should delete the ?callback=? , eg:

 var url = "ticker.js"; $.getJSON(url, function(data) { alert(data.price); }); 

If you look at $.getJSON() docs , do the following:

If the url contains the string "callback=?" in the url, the request is processed as JSONP. See the discussion of the jsonp data jsonp in $ for more details . Ajax () .

With JSONP, it expects randomFunctioName({ticket:'IBM',price:14.57}); in the response, not just JSON, but a function call ... so JSONP works in the cross-domain, being a <script> . Since you just want JSON and process it from a local source, remove the callback=? fragment callback=? .

Edit: I completely skipped the second problem, your current JSON is invalid and will not be able to perform the jQuery checks added in 1.4. It should be the following:

 { "ticket": "IBM", "price": 14.57 } 

You can check your JSON for authenticity here: http://www.jsonlint.com/

+6
source

Source: https://habr.com/ru/post/1315651/


All Articles