IT박스

angular.js에서 JSONP $ http.jsonp () 응답 구문 분석

itboxs 2020. 7. 24. 07:56
반응형

angular.js에서 JSONP $ http.jsonp () 응답 구문 분석


$http.jsonp()함수에 래핑 된 json을 성공적으로 반환하는 angular의 요청을 사용 하고 있습니다.

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

반환 된 함수 래핑 된 JSON에 액세스 / 구문 분석하는 방법은 무엇입니까?


업데이트 : Angular 1.6 이후

콜백 매개 변수 값의 위치를 ​​지정하기 위해 더 이상 JSON_CALLBACK 문자열을 자리 표시 자로 사용할 수 없습니다.

이제 다음과 같이 콜백을 정의해야합니다.

$http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})

를 통해 매개 변수 변경 / 액세스 / 선언 $http.defaults.jsonpCallbackParam, 기본값은callback

참고 : 또한 URL을 신뢰할 수있는 / 허용 목록에 추가해야합니다.

$sceDelegateProvider.resourceUrlWhitelist

또는 다음을 통해 명시 적으로 신뢰할 수 있습니다.

$sce.trustAsResourceUrl(url)

success/error되지 .

$http기존의 약속 방법 successerror사용되지 않으며 v1.6.0의에서 제거 될 예정입니다. 대신 표준 then 메소드를 사용하십시오. 경우 $httpProvider.useLegacyPromiseExtensions로 설정 false한 후 이러한 방법은 발생합니다 $http/legacy error.

사용하다:

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

이전 답변 : Angular 1.5.x 이전

당신이해야 할 일은 다음 callback=jsonp_callbackcallback=JSON_CALLBACK같이 변경 하는 것입니다.

var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";

그런 다음 .success반환이 성공하면 함수가 작동하는 것처럼 작동해야합니다.

이렇게하면 전역 공간을 더럽 히지 않아도됩니다. 여기 AngularJS 문서에 설명되어 있습니다 .

이 방법을 사용하도록 Matt Ball의 바이올린을 업데이트했습니다 : http://jsfiddle.net/subhaze/a4Rc2/114/

전체 예 :

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

가장 중요한 것은 내가 아주 잠시 이해하지 못했다는 요청이 있다는 것입니다 해야 AngularJS와의 때문에, "콜백 = JSON_CALLBACK"을 포함하는 수정 요청 URL , "JSON_CALLBACK"에 대한 고유 식별자를 대체. 서버 응답은 "JSON_CALLBACK"하드 코딩 대신 '콜백'매개 변수의 값을 사용해야합니다.

JSON_CALLBACK(json_response);  // wrong!

필자는 자체 PHP 서버 스크립트를 작성하고 있었으므로 원하는 함수 이름을 알고 요청에서 "callback = JSON_CALLBACK"을 전달할 필요가 없다고 생각했습니다. 큰 실수!

AngularJS는 요청의 "JSON_CALLBACK"을 고유 한 함수 이름 (예 : "callback = angular.callbacks._0")으로 바꾸고 서버 응답은 해당 값을 반환해야합니다.

angular.callbacks._0(json_response);

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:

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.


This should work just fine for you, so long as the function jsonp_callback is visible in the global scope:

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)


You still need to set callback in the 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.


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

In Angular template you can use it as

{{data}}

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


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:

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

참고URL : https://stackoverflow.com/questions/12066002/parsing-jsonp-http-jsonp-response-in-angular-js

반응형