Reputation: 7944
I am trying to get a JSONP response working using the following code...
$http.jsonp('http://example.com:8888/?callback=JSON_CALLBACK').success( function( response )
{
console.dir( response );
});
http://example.com:8888/?callback=JSON_CALLBACK returns the following via node.js
JSON_CALLBACK({ date:'2013-05-15T08:53:51.747Z' });
The header is being set in node.js like this....
res.writeHead(200, {'Content-Type': 'application/json'});
Yet the error I get in a Chrome console is this...
Uncaught ReferenceError: JSON_CALLBACK is not defined
However, weirdly, If I create the function window.JSON_CALLBACK(response)
it will run. But I thought that success is meant to do that on my behalf.
Upvotes: 5
Views: 8715
Reputation: 9217
Here is a quick and dirty solution. Instead of outputting JSON_CALLBACK({ date:'2013-05-15T08:53:51.747Z' })
, you can try to output angular.callbacks._0({ date:'2013-05-15T08:53:51.747Z' })
. I believe this is bug in Angular.
An alternative is to request your url this way:
$http({
method: 'JSONP',
url: 'https://something.com/' + '?callback=JSON_CALLBACK' + '&otherstuffs'
});
PS. If you use php backend, I noticed changing the name of the php file will sometimes have positive result (like instead of using index.php we can try api.php). Although it seems to be completely random (what name works and vise versa) - I think this has to do with how Angular read the url of the json.
It looks like the reason of this unfortunate bug is that Angular will replace the JSON_CALLBACK
to angular.callbacks._0
but it will fail sometimes due to its URL interpreter.
Additionally, even if it succeeded the server you are using may not support the ?callback=angular.callbacks._0
in the url (which is a common behavior among servers).
Upvotes: 0
Reputation: 166
I found this hack and it's work for me
//.........................ini: Hack /* Copy-Paste this code just before your $http request. */ var c = $window.angular.callbacks.counter.toString(36); $window['angularcallbacks_' + c] = function (data) { $window.angular.callbacks['_' + c](data); delete $window['angularcallbacks_' + c]; }; //.........................end: Hack //Your $http request $http.jsonp(url) .success(function(){ console.log("ok") }) .error(function(data, status, headers, config){ console.error("ko"); });
Upvotes: 0
Reputation: 1
See angular $resource with jsonp not working This issue have been opened in git: https://github.com/angular/angular.js/issues/1551
Upvotes: 0
Reputation: 3850
Your content-type header is not correct.
Use application/json
if what you return is plain JSON. JSONP is Javascript, so you should use application/javascript
Upvotes: 2