akronymn akronymn - 1 year ago 190
AngularJS Question

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

I am using angular's

request which is successfully returning json wrapped in a function:

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

success(function(data, status, headers, config) {
//what do I do here?
error(function(data, status, headers, config) {
$scope.error = true;

The problem is, I don't know how to access/parse the returned function-wrapped-JSON. Any guidance is much appreciated. Thanks!

Answer Source

All you should have to do is change callback=jsonp_callback to callback=JSON_CALLBACK like so:

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.

Doing it this way keeps you from having to dirty up the global space. This is documented in the AngularJS documentation here.

Updated Matt Ball's fiddle to use this method: 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";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download