Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

Angularjs JSONP not working

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';
$http.jsonp(url)
    .success(function(data){
       console.log('success');
    })
    .error(function () {
      console.log('error')
    });

The request fires ok and I am getting the response (with header Content-Type:application/json) in this format:

    [{"id": "1", "name": "John Doe"},
     {"id": "2", "name": "Lorem ipsum"},
     {"id": "3", "name": "Lorem ipsum"}]

Can you see anything wrong? Maybe the format I should return from the server is not right? Angular fires the error callback without any error message besides the one I set ('error').

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...