I try to send data using JSONP request in AngularJS.
$http({ method: 'jsonp',
url: '/?callback=JSON_CALLBACK', /// Add '?callback=JSON_CALLBACK'
data: JSON.stringify(request) })
.success(function (data, status, headers, config) { });
Is this possible?
I try to send data using JSONP request in AngularJS.
$http({ method: 'jsonp',
url: 'http://test.local/?callback=JSON_CALLBACK', /// Add '?callback=JSON_CALLBACK'
data: JSON.stringify(request) })
.success(function (data, status, headers, config) { });
Is this possible?
Share Improve this question edited Jul 1, 2015 at 23:58 JasonMArcher 15k22 gold badges59 silver badges53 bronze badges asked Sep 7, 2013 at 17:39 ExyTabExyTab 5573 gold badges7 silver badges14 bronze badges 1- in angularjs document they have provided the JSONP sample, that may helpful. docs.angularjs/api/ng.$http#methods_jsonp – Uttesh Kumar Commented Dec 21, 2013 at 3:48
2 Answers
Reset to default 9Yes it's possible see the $http.jsonp function. In short you should do something like
$http.jsonp('http://www.example.?callback=JSON_CALLBACK')
.success (function(data, ...) {
//your data here
...
})
Please be aware that you must set callback=JSON_CALLBACK as a query parameter of your http call in order for angular to do its magic.
To send data along with your request it will depend if you want query parameters (1), request message data (2) or both (3).
Case 1 :
$http.jsonp('http://www.example.?callback=JSON_CALLBACK', {params : Object | String})
as per documentation "Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified."
Case 2 :
$http.jsonp('http://www.example.?callback=JSON_CALLBACK', {data : Object | String})
Case 3 :
$http.jsonp('http://www.example.?callback=JSON_CALLBACK', {params : Object | String, data : Object | String})
Late answer, but: data
only works for POST
requests. However you can't make a POST
request with JSONP -- the way it works is it inserts a <script>
tag into your DOM with src
set to the URL of the request; when your browser evaluates the script it will call the callback parameter (Angular basically replaces JSON_CALLBACK
by a pointer to your success function).
TL;DR: the only way you can send stuff to the server using JSONP is using the params
key in the config.