3

我正在尝试从 twitter 获取 json 数据。http://api.twitter.com/1/statuses/public_timeline.json 这是我的代码

<html>
<head>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
    <script>
        $(document).ready(function(){

            $("button").click(function(){
                $.getJSON("http://api.twitter.com/1/statuses/public_timeline.json",function(result){
                    $.each(result, function(i, field){
                        $("div").append(field + " ");
                    });
                });
            });
        });
    </script>
</head>
<body>

<button>Get JSON data</button>
<div></div>

</body>
</html> 

它来自http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_getjson 但它不起作用!

4

4 回答 4

1

您在 JavaScript中以同源策略运行。这基本上是说,您无法访问来自不同域的资源(在您的情况下,另一个域是 twitter.com)。

一种解决方案是使用 JSONP。twitter API 支持这一点。在您的情况下,您可以使用 jQuery 运行 JSONP 请求,如下所示:

$.ajax({
  url: "http://api.twitter.com/1/statuses/public_timeline.json",
  cache: false,
  dataType: 'jsonp',
  success: function( result ){
    $.each(result, function(i, field){
                        $("div").append(field + " ");
                    });
  }
});

此外,w3schools 也不是可靠的信息来源。最好使用Mozilla Developer Network之类的东西。

于 2012-11-29T12:29:52.357 回答
0

查看您尝试加载的 json 文档。当我尝试访问它时,它返回以下错误:

{"errors":[{"message":"Sorry, that page does not exist","code":34}]}

在您担心代码片段是否正常工作之前,我会尝试用对 twitter 的有效 api 调用替换 url。:)

于 2012-11-29T12:29:43.740 回答
0

Cross-Origin由于资源共享,您尝试从其他域获取文档并且请求的 URL 阻止了您的请求。你可以在这里阅读:http ://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing

您可以将 JSONP 与 jQuery 一起使用,这应该允许您完成请求,但是您请求的页面会收到 404 错误,因此无论如何您可能对结果无能为力。

于 2012-11-29T12:29:55.973 回答
0

您可以使用 $.ajax() jquery 方法从其他域访问 json 数据。请参阅下面的代码示例

   $.ajax({

   url : " // twitter api url",
   dataType : "JSON",
   cache : false,
   success : function(success)
    {
     $.each(success, function(index,value) {$("div").append(value + ""); })
    }

   error : function() { //Statements for handling ajax errors }

   });

您在该 ajax 请求中使用的 url 返回一个包含错误的 json 数组

{"errors": [{"message": "The Twitter REST API v1 is no longer active. Please       
migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}

您需要在处理请求之前迁移到 API v1.1,将 twitter api url 替换为 API v1.1 中提供的新 json url

于 2013-07-04T06:33:57.037 回答