Angularjs JSONP not working

前端 未结 3 1140
抹茶落季
抹茶落季 2020-11-29 03:12

I might be missing something here but I can\'t make this JSONP request work, here is the code:

var url =  \'http://\' + server + \'?callback=JSON_CALLBACK\';         


        
相关标签:
3条回答
  • 2020-11-29 03:46

    @TheHippo is correct the data should not just be a plain json response. Here is a working example of a JSONP request against a youtube endpoint in AngularJS.

    A couple of things to note in this example:

    • Angular's $http.jsonp converts the request querystring parameter from callback=JSON_CALLBACK to callback=angular.callbacks._0.
    • When calling the youtube endpoint I needed to specify to the service that this is a JSONP request by using alt=json-in-script instead of alt=json in the querystring. This was found in their documentation.
    • Compare the results of this url to this one to see the difference between JSON and JSONP response in your browser.
    • Take a look at the Chrome Network Panel in Developer Tools to help compare and troubleshoot with your request/response.

    I know this example is very specific but hopefully it helps!

    0 讨论(0)
  • 2020-11-29 03:53

    JSONP requires you do wrap your data into a JavaScript function call. So technically you return a JavaScript file and not a Json file.

    The data returned from server should similar to this:

    // the name should match the one you add to the url
    JSON_CALLBACK([
        {"id": "1", "name": "John Doe"},
        {"id": "2", "name": "Lorem ipsum"},
        {"id": "3", "name": "Lorem ipsum"}
    ]);
    

    Edit: If some one else stumbles across problems with angular's JSONP please also read this answer to this question, it contains usefull informations about how angular handles the actual callback function.

    0 讨论(0)
  • 2020-11-29 03:56

    If the response data is "pure" JSON, we can just handle it with angular's $http.get.

    $http.get(url).
      then(function(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.responseArray = response.data;
     }, function(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
     });
    

    Refer to the example on w3schools

    0 讨论(0)
提交回复
热议问题