问题描述
我正在尝试从 JSONP 端点获取一些数据.看起来数据正在响应中返回,但 Angular 仍然抛出错误.
Im trying to grab some data from a JSONP endpoint. It looks like the data is being returned in the response but Angular nonetheless throws an error.
var url = "https://careers.icims.com/jobs-api/"
var trustedUrl = $sce.trustAsResourceUrl(url);
$http.jsonp(trustedUrl, {jsonpCallbackParam: 'jobs'}).then(function(res){
console.log(res); // this is never executed :.(
});
我收到以下错误:Uncaught ReferenceError: jobs is not defined在jobs-api?jobs=angular.callbacks._0:1
其中 jobs
指的是我的 JSONP 前缀
I am getting the following error: Uncaught ReferenceError: jobs is not defined at jobs-api?jobs=angular.callbacks._0:1
where jobs
refers to my JSONP prefix
然而响应返回了 JSONP 脚本:
Yet the response returns the JSONP script:
为什么会抛出这个异常以及如何清除它?我使用的是 Angular 1.6.0
Why is this exception being thrown and how can it be cleared? I am on Angular 1.6.0
推荐答案
Not a Legal JSONP API
该 URL 上的 API 不是合法的 JSONP API.
它可以通过危险的服务获得:
It can be gotten with a dangerous service:
app.service("dangerousAPI", function($q) {
this.get = get;
function get(funcName, url) {
var dataDefer = $q.defer();
window[funcName] = function(x) {
dataDefer.resolve(x);
}
var tag = document.createElement("script");
tag.src = url;
document.getElementsByTagName("head")[0].appendChild(tag);
return dataDefer.promise;
}
})
使用风险自负.
angular.module("app",[])
.service("dangerousAPI", function($q) {
this.get = get;
function get(funcName, url) {
var dataDefer = $q.defer();
window[funcName] = function(x) {
dataDefer.resolve(x);
}
var tag = document.createElement("script");
tag.src = url;
document.getElementsByTagName("head")[0].appendChild(tag);
return dataDefer.promise;
}
})
.run(function($rootScope, dangerousAPI) {
var url = "https://careers.icims.com/jobs-api/";
dangerousAPI.get('jobs',url).then(function(data) {
$rootScope.data = data;
})
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>Dangerous API DEMO</h1>
<pre>{{data | json}}</pre>
</body>
这篇关于不是合法的 JSONP API——如何在没有 CALLBACK 参数的情况下获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!