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

时间:2021-07-14 12:13:51

I am using angular's $http.jsonp() request which is successfully returning json wrapped in a function:

我使用的是角的$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?

如何访问/解析返回的函数-wrapped- json ?

8 个解决方案

#1


293  

UPDATE: since Angular 1.6

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(一些/信任/ url”,{ jsonpCallbackParam:“回调”})

Change/access/declare param via $http.defaults.jsonpCallbackParam, defaults to callback

更改/访问/声明param通过$http.default . jsonpcallbackparam,默认为回调。

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.

成功/错误被弃用。

The $http legacy promise methods success and error have been deprecated and will be removed in v1.6.0. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

$http legacy承诺方法成功和错误已被弃用,将在v1.6.0中删除。用标准的方法代替。如果httpProvider美元。useLegacyPromiseExtensions设置为false,然后这些方法将抛出$http/遗留错误。

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

之前的回答: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);
    });

#2


69  

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

#3


8  

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:

这是非常有用的。角度不像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.

然后在您的角度模板中显示或操作{{data}}。

#4


5  

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代码)

#5


4  

You still need to set callback in the params:

您仍然需要在params中设置回调:

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”是对全局定义函数的严格引用。您可以在您的角度脚本之外定义它,然后在您的模块中重新定义它。

#6


2  

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(数据);

In Angular template you can use it as

在角模板中,你可以使用它。

{{data}}

#7


0  

for me the above solutions worked only once i added "format=jsonp" to the request parameters.

对于我来说,上面的解决方案只在请求参数中添加了“format=jsonp”。

#8


0  

I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:

我使用的是角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);
    });

#1


293  

UPDATE: since Angular 1.6

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(一些/信任/ url”,{ jsonpCallbackParam:“回调”})

Change/access/declare param via $http.defaults.jsonpCallbackParam, defaults to callback

更改/访问/声明param通过$http.default . jsonpcallbackparam,默认为回调。

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.

成功/错误被弃用。

The $http legacy promise methods success and error have been deprecated and will be removed in v1.6.0. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

$http legacy承诺方法成功和错误已被弃用,将在v1.6.0中删除。用标准的方法代替。如果httpProvider美元。useLegacyPromiseExtensions设置为false,然后这些方法将抛出$http/遗留错误。

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

之前的回答: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);
    });

#2


69  

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

#3


8  

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:

这是非常有用的。角度不像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.

然后在您的角度模板中显示或操作{{data}}。

#4


5  

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代码)

#5


4  

You still need to set callback in the params:

您仍然需要在params中设置回调:

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”是对全局定义函数的严格引用。您可以在您的角度脚本之外定义它,然后在您的模块中重新定义它。

#6


2  

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(数据);

In Angular template you can use it as

在角模板中,你可以使用它。

{{data}}

#7


0  

for me the above solutions worked only once i added "format=jsonp" to the request parameters.

对于我来说,上面的解决方案只在请求参数中添加了“format=jsonp”。

#8


0  

I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:

我使用的是角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);
    });