问题描述
我试图从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 :.(
});
我得到以下信息错误:未捕获的ReferenceError:作业未定义
at 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
推荐答案
不是合法的JSONP API
该URL的API不是
它可以带有危险的se服务:
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;
}
})
使用风险由您自行承担。
Use at your own risk.
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参数的情况下获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!