简体   繁体   English

解析angular.js中的JSONP $ http.jsonp()响应

[英]parsing JSONP $http.jsonp() response in angular.js

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?

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'})

Change/access/declare param via $http.defaults.jsonpCallbackParam , defaults to callback 通过$http.defaults.jsonpCallbackParam更改/访问/声明参数,默认为callback

Note: You must also make sure your URL is added to the trusted/whitelist: 注意:您还必须确保将您的网址添加到可信/白名单中:

$sceDelegateProvider.resourceUrlWhitelist

or explicitly trusted via: 或明确信任通过:

$sce.trustAsResourceUrl(url)

success/error were deprecated . success/error已被弃用

The $http legacy promise methods success and error have been deprecated and will be removed in v1.6.0. $http遗留承诺方法successerror已被弃用,将在v1.6.0中删除。 Use the standard then method instead. 请改用标准方法。 If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error . 如果$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);
    });

The MOST IMPORTANT THING I didn't understand for quite awhile is that the request MUST contain "callback=JSON_CALLBACK", because AngularJS modifies the request url , substituting a unique identifier for "JSON_CALLBACK". 最重要的是我很久没理解的是请求必须包含“callback = JSON_CALLBACK”,因为AngularJS 修改请求url ,用唯一标识符替换“JSON_CALLBACK”。 The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK": 服务器响应必须使用'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. 由于我正在编写自己的PHP服务器脚本,我以为我知道它想要的函数名称,并且不需要在请求中传递“callback = JSON_CALLBACK”。 Big mistake! 大错!

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);

This was very helpful. 这非常有帮助。 Angular doesn't work exactly like JQuery. Angular不像JQuery那样工作。 It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. 它有自己的jsonp()方法,在查询字符串的末尾确实需要“&callback = JSON_CALLBACK”。 Here's an example: 这是一个例子:

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}}。

This should work just fine for you, so long as the function jsonp_callback is visible in the global scope: 只要函数jsonp_callback在全局范围内可见,这对您来说应该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代码)

You still need to set callback in the params: 你仍然需要在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. 其中'functionName'是对全局定义函数的字符串化引用。 You can define it outside of your angular script and then redefine it in your module. 您可以在角度脚本之外定义它,然后在模块中重新定义它。

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}}

对我来说,上面的解决方案只有一次我将“format = jsonp”添加到请求参数。

I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. 我正在使用角1.6.4并且subhaze提供的答案对我不起作用。 I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl . 我修改了一下然后它工作了 - 你必须使用$ sce.trustAsResourceUrl返回的值。 Full code: 完整代码:

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);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM