Angular JSONP calling WordPress JSON REST API

≡放荡痞女 提交于 2020-01-06 18:07:24

问题


I'm not entirely sure what's going on, as I'm still trying to figure cross domain javascript calls, but I'm calling some JSON from a WordPress site (that's using the WordPress JSON REST API plugin). Since it's coming from a local site (I'm working on a mobile app using Ionic/Angular), I've had some cross-domain access issues. So, I'm looking at using JSONP.

I've successfully called and returned info, but I can't seem to do anything with the returned data.

My call is as so:

$http.jsonp('http://heavymetalhamilton.ca/wp-json/hmh-api/shows?_jsonp&callback=JSON_CALLBACK')
  .success(function(data) {
    console.log(data);
  });

However, nothing is being logged. I can see that the $http.jsonp call is returning data (I can see in developer tools and looks like this:

/**/([{"ID":30,"post_date":"2014-09-25 18:33:15","post_date_gmt":"2014-09-25 
...
)

I see that the returning data has some packing around it, but I'm not sure how to process this data.

Any help?

EDIT: Have what's happening going on in a CodePen


回答1:


So, the biggest problem I had (there were a couple), was my jsonp call. There isn't a "success" promise attached to it. Jsonp fires a function defined as a callback - in this case, the call to:

http://heavymetalhamilton.ca/wp-json/hmh-api/shows?_jsonp=mytest&callback=JSON_CALLBACK

calls a global function of mytest() once returned. So, in order to get a global function in my controller, so I can use $scope, my end result is:

$http.jsonp('http://heavymetalhamilton.ca/wp-json/hmh-api/shows?_jsonp=mytest&callback=JSON_CALLBACK');

window.mytest = function(data) {
  $scope.shows = data;
};

I also had an issue with the content type I was returning (as mentioned by @Miszy). I have to specify that the Content-Type is set to application/javascript... previously it was returning application/json.

In my case, I'm writing some custom functionality to return specific content, so I added the following:

if ($_GET['_jsonp']) {
   $response->header( 'Content-Type', 'application/javascript; charset=' . get_option( 'blog_charset' ), true );
}

Hope this helps someone down the road!




回答2:


The data returns as a JSON object. Please try to log using the following format

JSON.stringify(data);

Or else you can go through the returned data set in the following manner

console.log(data.ID + ', ' + data.post_date);

and so on...



来源:https://stackoverflow.com/questions/26598306/angular-jsonp-calling-wordpress-json-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!