javascript - AngularJS 从其他域请求 JSON

标签 javascript ajax json angularjs cors

我正在尝试使用以下代码从 Wikia API 检索数据。但一切似乎都失败了。据我了解,必须在服务器上启用 CORS,我试图从中检索数据。不过我不知道维基百科是不是这样。所以JSONP似乎是唯一的方法。但我收到错误

XMLHttpRequest 无法加载 http://adventuretime.wikia.com/api/v1/Articles/List?expand=1&category=Episodes&limit=200。请求的资源上不存在“Access-Control-Allow-Origin” header 。因此,不允许访问来源“http://website.com”。

我已阅读 AngularJS 文档:https://docs.angularjs.org/api/ng/service/ $http

w3schools:http://www.w3schools.com/angular/angular_http.asp

还有关于 stackoverflow 的大量问题。我的代码有什么可怕的错误吗? Angular 应该原生支持 CORS 和 JSONP 请求

我的代码如下:

Index.html

<!DOCTYPE html>
<html ng-app="episodes">
<head>
    <meta charset="UTF-8">
    <title>Episodes</title>
    <script src="angular.js"></script>
    <script src="workshop.js"></script>
</head>
<body ng-controller="AppController as app">

    <table>
        <thead> 
            <tr>
                <th>Title</th>
                <th>Url</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="episode in app.episodes">
                <td>{{episode.title}}</td>
                <td>{{episode.url}}</td>
            </tr>
        </tbody>
    </table>

</body>
</html>

workshop.js

(function(){
    angular
        .module('episodes', [])
        .controller('AppController', function($http){
            var app = this;

            app.episodes = $http({
                url: "http://adventuretime.wikia.com/api/v1/Articles/List?expand=1&category=Episodes&limit=200",
                dataType: "jsonp"
            });

        });
})();

感谢任何帮助!

预先感谢您的帮助

编辑

响应 header 是:

Content-Encoding: gzip
X-Content-Type-Options: nosniff
X-Cacheable: YES
Age: 0
X-Cache: ORIGIN, MISS, MISS
Content-Length: 21965
X-Served-By: ap-s21, cache-wk-sjc3160-WIKIA, cache-fra1233-FRA
X-Backend-Response-Time: 2.267
Server: Apache
X-Timer: S1439118796.704444,VS0,VE2447
Vary: Accept-Encoding
Content-Type: application/json; charset=utf-8
Cache-Control: public, max-age=86400
Accept-Ranges: bytes
X-Cache-Hits: ORIGIN, 0, 0

最佳答案

尝试使用$http.jsonp(url);进行跨域请求;

Angularjs api - $http.jsonp();

关于javascript - AngularJS 从其他域请求 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31899651/

相关文章:

java - Gson 序列化/反序列化映射到/从 KeyValuePairs 列表

JavaScript 更新进度值时出错

javascript - 使用箭头键盘而不是鼠标时 ng-options 模型未更新

JavaScript : Getting the dom image data source and save it to directory

javascript - window.location.reload(true) 重新加载页面,但页面需要刷新才能显示更改

php - 响应正常,但 $.ajax 上的成功方法未触发?

javascript - Aurelia npm 安装 : tons of "gyp ERR"

javascript - 带有 Action 的颜色框内的元素

java - 从 Jsp 发送 Json 数据到 Rest Controller 时出现 415(不支持的媒体类型错误)

java - JSONException : Issues trying to retrieve data from JSON