0

我正在尝试从一个站点捕获一些 JSON 信息。

我的第一个例子只是一个测试和工作:

<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>

但问题在于我的第二个示例:

<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 - 我正在尝试从页面获取信息以在博客中使用它:)

4

1 回答 1

0

带有 jQ​​uery 的外部 JSON 意味着使用 JSONP。这可以通过页面返回一个 Javascript 脚本来实现,该脚本使用您需要的数据调用一个函数(您定义的)。您无法像普通 JSON 一样获取数据。所以响应需要如下所示:

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}});

而不是

{"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}}

(该函数不会被调用json_callback,但每次都会有一个唯一的名称。)

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.

于 2013-03-30T14:28:32.633 回答