简体   繁体   中英

Loading external JSON with Javascript

I'm trying to catch some JSON info from a site.

My first exemple its just a test and work:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.get("http://www.w3schools.com/jquery/demo_test.asp",function(data,status){
      document.write("Data: " + data + "\n<br>Status: " + status);
    });
});
</script>

But the problem its in my second example:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.get("https://btc-e.com/api/2/ltc_usd/ticker",function(data,status){
      document.write("Data: " + data + "\n<br>Status: " + status);
    });
});
</script>

PS - i'm trying to get the info from the page to use it in a blog :)

External JSON with jQuery means using JSONP. This works by the page returning a Javascript script instead, which calls a function (which you define) with the data you need. You can't get the data as normal JSON. So the response needs to look like this:

json_callback({"ticker":{"high":0.77,"low":0.64,"avg":0.705,"vol":107049.5563,"vol_cur":151754.22482,"last":0.76,"buy":0.766,"sell":0.75811,"server_time":1364653244}});

rather than

{"ticker":{"high":0.77,"low":0.64,"avg":0.705,"vol":107049.5563,"vol_cur":151754.22482,"last":0.76,"buy":0.766,"sell":0.75811,"server_time":1364653244}}

(The function would not be called json_callback , but would have a unique name each time.)

This obviously relies on the server's assistance, so the server needs to be set up to support JSONP. The normal way of indicating this is by adding callback=? to the end of the URL, where ? is the name of the function you want to call. If we try this , you'll see that the script does not change. This indicates that the website does not support JSONP requests, so there is no way of accessing this data using JSONP.

There are various other methods of getting the data. The simplest is probably proxying the data from the external server with your own server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM