Ho questo pezzo di codice jQuery che funziona bene con l'origine incrociata:
jQuery.ajax({
url: "http://example.appspot.com/rest/app",
type: "POST",
data: JSON.stringify({"foo":"bar"}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log("success");
},
error: function (response) {
console.log("failed");
}
});
Ora sto cercando di convertirlo in codice Angular.js senza alcun successo:
$http({
url: "http://example.appspot.com/rest/app",
dataType: "json",
method: "POST",
data: JSON.stringify({"foo":"bar"}),
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).success(function(response){
$scope.response = response;
}).error(function(error){
$scope.error = error;
});
Qualsiasi aiuto apprezzato.
- Endless
Il modo in cui AngularJS chiama $http sarebbe simile a:
$http({
url: "http://example.appspot.com/rest/app",
method: "POST",
data: {"foo":"bar"}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.data = response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.error = response.statusText;
});
o potrebbe essere scritto in modo ancora più semplice utilizzando metodi di scelta rapida:
$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);
Ci sono molte cose da notare:
success
e error
(si prega di notare anche i parametri di ogni callback) - Deprecate in angular v1.5then
. then
sono disponibili qui Quello sopra è solo un rapido esempio e alcuni suggerimenti, assicurati di controllare la documentazione di AngularJS per ulteriori informazioni: http://docs.angularjs.org/api/ng.$http