Javascript 在 angular.js 中解析 JSONP $http.jsonp() 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12066002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parsing JSONP $http.jsonp() response in angular.js
提问by akronymn
I am using angular's $http.jsonp()
request which is successfully returning json wrapped in a function:
我正在使用 angular 的$http.jsonp()
请求,它成功返回包装在函数中的 json:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";
$http.jsonp(url).
success(function(data, status, headers, config) {
//what do I do here?
}).
error(function(data, status, headers, config) {
$scope.error = true;
});
How to access/parse the returned function-wrapped-JSON?
如何访问/解析返回的函数包装 JSON?
回答by subhaze
UPDATE: since Angular 1.6
更新:从 Angular 1.6 开始
You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go
您不能再使用 JSON_CALLBACK 字符串作为占位符来指定回调参数值的位置
You must now define the callback like so:
您现在必须像这样定义回调:
$http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
$http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
Change/access/declare param via $http.defaults.jsonpCallbackParam
, defaults to callback
更改/访问/声明参数 via $http.defaults.jsonpCallbackParam
,默认为callback
Note: You must also make sure your URL is added to the trusted/whitelist:
注意:您还必须确保您的 URL 已添加到受信任/白名单:
$sceDelegateProvider.resourceUrlWhitelist
$sceDelegateProvider.resourceUrlWhitelist
or explicitly trusted via:
或通过以下方式明确信任:
$sce.trustAsResourceUrl(url)
$sce.trustAsResourceUrl(url)
success/error
were deprecated.
success/error
被弃用。
The
$http
legacy promise methodssuccess
anderror
have been deprecated and will be removed in v1.6.0. Use the standard then method instead. If$httpProvider.useLegacyPromiseExtensions
is set tofalse
then these methods will throw$http/legacy error
.
在
$http
传统方法的承诺success
,并error
已被弃用,并将在V1.6.0被删除。请改用标准 then 方法。如果$httpProvider.useLegacyPromiseExtensions
设置为,false
则这些方法将抛出$http/legacy error
。
USE:
用:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
var trustedUrl = $sce.trustAsResourceUrl(url);
$http.jsonp(trustedUrl, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});
Previous Answer: Angular 1.5.x and before
上一个答案:Angular 1.5.x 及之前版本
All you should have to do is change callback=jsonp_callback
to callback=JSON_CALLBACK
like so:
你所要做的就是改变callback=jsonp_callback
成callback=JSON_CALLBACK
这样:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
And then your .success
function should fire like you have it if the return was successful.
然后.success
,如果返回成功,您的函数应该像您一样触发。
Doing it this way keeps you from having to dirty up the global space. This is documented in the AngularJS documentation here.
这样做可以使您不必弄脏全局空间。这在此处的 AngularJS 文档中有所记录。
Updated Matt Ball's fiddle to use this method: http://jsfiddle.net/subhaze/a4Rc2/114/
更新 Matt Ball 的小提琴以使用此方法:http: //jsfiddle.net/subhaze/a4Rc2/114/
Full example:
完整示例:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
});
回答by Joseph Oster
The MOST IMPORTANT THINGI didn't understand for quite awhile is that the request MUSTcontain "callback=JSON_CALLBACK", because AngularJS modifies the request url, substituting a unique identifier for "JSON_CALLBACK". The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK":
很长一段时间我都没有理解的最重要的事情是请求必须包含“callback=JSON_CALLBACK”,因为 AngularJS修改了请求 url,用唯一标识符替换“JSON_CALLBACK”。服务器响应必须使用“回调”参数的值,而不是硬编码“JSON_CALLBACK”:
JSON_CALLBACK(json_response); // wrong!
Since I was writing my own PHP server script, I thought I knew what function name it wanted and didn't need to pass "callback=JSON_CALLBACK" in the request. Big mistake!
由于我正在编写自己的 PHP 服务器脚本,因此我认为我知道它想要什么函数名称并且不需要在请求中传递“callback=JSON_CALLBACK”。大错!
AngularJS replaces "JSON_CALLBACK" in the request with a unique function name (like "callback=angular.callbacks._0"), and the server response must return that value:
AngularJS 将请求中的“JSON_CALLBACK”替换为唯一的函数名称(如“callback=angular.callbacks._0”),并且服务器响应必须返回该值:
angular.callbacks._0(json_response);
回答by Peter
This was very helpful. Angular doesn't work exactly like JQuery. It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. Here's an example:
这非常有帮助。Angular 不像 JQuery 那样工作。它有自己的 jsonp() 方法,它确实需要在查询字符串的末尾加上“&callback=JSON_CALLBACK”。下面是一个例子:
var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
$http.jsonp('http://librivox.org/api/feed/audiobooks/author/Melville?format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
Then display or manipulate {{ data }} in your Angular template.
然后在您的 Angular 模板中显示或操作 {{ data }}。
回答by Matt Ball
This should work just fine for you, so long as the function jsonp_callback
is visible in the global scope:
只要该函数jsonp_callback
在全局范围内可见,这对您来说应该很好用:
function jsonp_callback(data) {
// returning from async callbacks is (generally) meaningless
console.log(data.found);
}
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";
$http.jsonp(url);
Full demo: http://jsfiddle.net/mattball/a4Rc2/(disclaimer: I've never written any AngularJS code before)
完整演示:http: //jsfiddle.net/mattball/a4Rc2/(免责声明:我以前从未写过任何 AngularJS 代码)
回答by paradite
You still need to set callback
in the params:
您仍然需要callback
在参数中设置:
var params = {
'a': b,
'token_auth': TOKEN,
'callback': 'functionName'
};
$sce.trustAsResourceUrl(url);
$http.jsonp(url, {
params: params
});
Where 'functionName' is a stringified reference to globally defined function. You can define it outside of your angular script and then redefine it in your module.
其中“functionName”是对全局定义函数的字符串化引用。您可以在 angular 脚本之外定义它,然后在您的模块中重新定义它。
回答by kapil
For parsing do this-
为了解析做这个 -
$http.jsonp(url).
success(function(data, status, headers, config) {
//what do I do here?
$scope.data=data;
}).
Or you can use `$scope.data=JSON.Stringify(data);
或者你可以使用`$scope.data=JSON.Stringify(data);
In Angular template you can use it as
在 Angular 模板中,您可以将其用作
{{data}}
回答by Tali
for me the above solutions worked only once i added "format=jsonp" to the request parameters.
对我来说,上述解决方案仅在我将“format=jsonp”添加到请求参数后才起作用。
回答by mikatuo
I'm using angular 1.6.4 and answer provided by subhazedidn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:
我正在使用 angular 1.6.4 并且subhaze提供的答案对我不起作用。我稍微修改了它然后它起作用了 - 你必须使用$sce.trustAsResourceUrl返回的值。完整代码:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
url = $sce.trustAsResourceUrl(url);
$http.jsonp(url, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});