I have such jQuery Ajax request. I need to turn it into an AngularJS $http request. How can I do that?
$.ajax({
type: "POST",
dataType: "jsonp",
crossDomain: false,
data:{
user: username,
pass: password
},
beforeSend: function (request){
request.setRequestHeader("Accept-Language", languageCode);
},
url: someUrl
})
.done(function (data, textStatus, jqXHR){
console.log(data);
})
.fail(function (jqXHR, textStatus){
console.log("failed");
});
My Angular Implementations
Response {"data" : "", "status" : "200", "config" : .... } Data is empty
login : function (username, password) {
return $http({
method: 'POST',
url: someUrl,
data: {
user: username,
pass: password
},
headers: {
'Accept-Language': languageCode
}
})
}
I succeeded to get data wrapped in JSON_CALLBACK with next request. But I don't know how to call that callback. It is not done automatically. Response looks like {data:"JSON_CALLBACK({mydata})"...}
login : function (username, password) {
var url = someUrl
+ '?callback=JSON_CALLBACK&user=' + username
+ '&pass=' + password;
return $http.post(url);
},
Please refer to $http documentation. but here is somewhat counterpart for that jquery request
$http({
method: 'POST',
url: '/someUrl',
data: {
user: username,
pass: password
},
headers: {
'Accept-Language':languageCode
}
}).then(function successCallback(response) {
//do something
}, function errorCallback(response) {
//do something
});
There is no such thing as a JSONP POST request. When jQuery sees dataType: jsonp
, it ignores the method
propery and uses a script GET request. The data is added as parameters of the URL.
In AngularJS, JSONP requests are specified with method: 'JSONP
. The callback parameter needs to be JSON_CALLBACK
and must be capitalized.
login : function (username, password) {
return $http({
//method: 'POST',
method: 'JSONP',
url: someUrl,
//data: {
params: {
user: username,
pass: password,
callback: "JSON_CALLBACK"
},
headers: {
'Accept-Language': languageCode
}
})
}
Be aware that since the data is sent as URL parameters, sensitive information such as passwords are vulnerable to snooping attacks.
To demonstrate on JSFiddle:
var url="//jsfiddle.net/echo/jsonp/";
var params = { user: "myUser",
pass: "123456",
callback: "JSON_CALLBACK"
};
$http.jsonp(url, { params: params} )
.then(function onSuccess(response) {
$scope.response = response;
console.log(response);
})
The DEMO on JSFiddle .
AngularJS error .success is not a function
Might have something to do with it??
What API are you working with?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.