parsing JSONP $http.jsonp() response in angular.js
UPDATE: since Angular 1.6
You can no longer use the JSON_CALLBACK string as a placeholder for
specifying where the callback parameter value should go
You must now define the callback like so:
$http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
Change/access/declare param via $http.defaults.jsonpCallbackParam
, defaults to callback
Note: You must also make sure your URL is added to the trusted/whitelist:
$sceDelegateProvider.resourceUrlWhitelist
or explicitly trusted via:
$sce.trustAsResourceUrl(url)
success/error
were deprecated.
The
$http
legacy promise methodssuccess
anderror
have been deprecated and will be removed in v1.6.0. Use the standard then method instead. If$httpProvider.useLegacyPromiseExtensions
is set tofalse
then these methods will throw$http/legacy error
.
USE:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
var trustedUrl = $sce.trustAsResourceUrl(url);
$http.jsonp(trustedUrl, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});
Previous Answer: Angular 1.5.x and before
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";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
});
how to custom set angularjs jsonp callback name?
The callback names are hard-coded here httpBackend.js#L55, so you can't config it.
But, you could write a HTTP interceptor to workaround it like this:
.factory('jsonpInterceptor', function($timeout, $window, $q) {
return {
'request': function(config) {
if (config.method === 'JSONP') {
var callbackId = angular.callbacks.counter.toString(36);
config.callbackName = 'angular_callbacks_' + callbackId;
config.url = config.url.replace('JSON_CALLBACK', config.callbackName);
$timeout(function() {
$window[config.callbackName] = angular.callbacks['_' + callbackId];
}, 0, false);
}
return config;
},
'response': function(response) {
var config = response.config;
if (config.method === 'JSONP') {
delete $window[config.callbackName]; // cleanup
}
return response;
},
'responseError': function(rejection) {
var config = rejection.config;
if (config.method === 'JSONP') {
delete $window[config.callbackName]; // cleanup
}
return $q.reject(rejection);
}
};
})
Example Plunker: http://plnkr.co/edit/S5K46izpIxHat3gLqvu7?p=preview
Hope this helps.
Pass data from JSONP callback function to Angular controller
i came up this solution after searching and trying ,in your case this solution is better than
other solutions that use angular.element(....).scope()
because here we use angular service $window
while in (angular.element().scope) we use something may be disabled in some angular mode, check this.
CBR_XML_Daily_Ru = function(data) {
window.angularJsonpCallBackDefindInController(data);
};
var myApp = angular.module('myApp', []).controller('myCtrl', myCtrl);
function myCtrl($scope, $http,$window) {
var self = this;
$http.jsonp('https://www.cbr-xml-daily.ru/daily_jsonp.js?callback=JSON_CALLBACK');
$window.angularJsonpCallBackDefindInController = function (data) {
//u can do anything here, you are in the controller, and in the same time this function in the window object and get called from anywhere even in jquery
self.divForCharCode = data.Valute.EUR.CharCode;
};
}
you can also use this way to execute function in controller from jquery "scope":
CBR_XML_Daily_Ru = function(data) {
angular.element("#controllerDivId").controller().angularJsonpCallBackDefindInController(data);
};
var myApp = angular.module('myApp', []).controller('myCtrl', myCtrl);
function myCtrl($scope, $http,$window) {
var self = this;
$http.jsonp('https://www.cbr-xml-daily.ru/daily_jsonp.js?callback=JSON_CALLBACK');
self.angularJsonpCallBackDefindInController = function (data) {
self.divForCharCode = data.Valute.EUR.CharCode;
};
}
this is the html (you need to include jquery to use the second solution)
<html>
<head>
<script src="jquery-3.1.1.min.js"></script>
<script src="angular.min.js"></script>
<!--<link rel="stylesheet" href="style.css" />-->
<script src="jsnopstuff.js"></script>
</head>
<body>
<div id="controllerDivId" ng-controller='myCtrl as ctrl' ng-app='myApp'>
<input type=text ng-model='ctrl.divForCharCode'>
<div id='div1'></div>
</div>
</body>
</html>
Angularjs JSONP not working
JSONP requires you do wrap your data into a JavaScript function call. So technically you return a JavaScript file and not a Json file.
The data returned from server should similar to this:
// the name should match the one you add to the url
JSON_CALLBACK([
{"id": "1", "name": "John Doe"},
{"id": "2", "name": "Lorem ipsum"},
{"id": "3", "name": "Lorem ipsum"}
]);
Edit: If some one else stumbles across problems with angular's JSONP please also read this answer to this question, it contains usefull informations about how angular handles the actual callback function.
AngularJS: Unable to Send $Http JSON Response to View
Edit: I made this plunker to help you!
http://embed.plnkr.co/Yiz9TvVR4Wcf3dLKz0H9/
If I were you, I would use the service function to update the own service value. You already created this.result
, you can just update its value.
Your Service:
myApp.service('apiService', ['$http', function($http)
{
var api = "http://domain.xpto/api/";
var self = this;
this.result = {};
this.getSection = function(id){
var url = api + "section/" + id;
$http.get(url).then(function(res){
self.result = res;
});
}
}]);
I wouldn't use a Promise for this case. You can access the Service's var into your Controller and View.
Your controller:
myApp.controller('mainController', ['$scope', '$routeParams', 'apiService',
function($scope, $routeParams, apiService)
{
$scope.apiSer = apiService;
$scope.apiSer.getSection(1);
}]);
In your View:
<pre>{{ apiSer.result }}</pre>
And now you'll see your parameter get updated in real time.
How to unit test functions with $http.jsonp in AngularJS?
After calling scope.login()
and before your expect(...)
, you need to call $httpBackend.flush()
for it to respond with the specified expectations.
This is not specific to JSONP, but unit testing $http
calls in general.
To summarize, here are the steps to unit test code that makes $http
requests:
- Set up your expectations using
$httpBackend
. - Invoke the code that makes the
$http
call(s). - Call
$httpBackend.flush()
to make it respond to any pending requests with the expectations you set up. - Make your test assertions.
See the docs regarding flush.
Related Topics
Where's the Connection Between Index.HTML and Index.Js in a Create-React-App Application
Pass a JavaScript Variable Value into Input Type Hidden Value
How to Toggle Class Using Pure JavaScript in HTML
How to Add "Href" Attribute to a Link Dynamically Using JavaScript
What Is a Text Node, Its Uses? //Document.Createtextnode()
How to Change the Background Image of Div Using JavaScript
JavaScript Detect Click Event Outside of Div
When Loading an HTML Page via Ajax, Will Script Tags Be Loaded
How to Resize HTML Canvas Element
How to Retain the Scroll Position of a Scrollable Area When Pressing Back Button
Making Sure at Least One Checkbox Is Checked
How to Append Timestamp to the JavaScript File in <Script> Tag Url to Avoid Caching
Get Element Stylesheet Style in JavaScript
Open a New JavaScript Window(.Open) Along with Its CSS Styling
Why Browser Is Returning Empty String on Style.Height ? How to Get Actual Height of an Element
Position Fixed Not Working in Mobile Browser
Angularjs- Login and Authentication in Each Route and Controller