[AngularJS] solution for jsonp not working

I got to try a http jsonp call an external url in AngularJS :

    .error(function () {

Using jsonp and adding the “callback=JSON_CALLBACK” to the end of the url allows me to call an external url.
NB. Calling an external url by $http.get will return an “Cross-Origin Request Blocked” error.

My json file in /var/www is like this (only for test):

[{"id": "1"},
 {"id": "2"},
 {"id": "3"}

But the call always return an error 😦

The reasons are (original answers from stackoverflow):
1. JSONP requires you do wrap your data into a JavaScript function call. So technically you return a JavaScript file and not a Json file. So my json file becomes :

JSON_CALLBACK([{"id": "1"},
 {"id": "2"},
 {"id": "3"}

2. Angular’s $http.jsonp converts the request query string parameter from callback=JSON_CALLBACK to callback=angular.callbacks._0. So I modified JSON_CALLBACK to angular.callbacks._0, and it works.

angular.callbacks._0([{"id": "1"},
 {"id": "2"},
 {"id": "3"}

This won’t be a permenant solution, I have to run futher to find something which can be industrial. But the answer in this post already helps .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s