Tengo esta pieza de código jQuery que funciona bien origen cruzado:
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"); } });
Ahora estoy tratando de convertir esto a código Angular.js sin ningún éxito:
$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; });
Cualquier ayuda apreciada.
La forma de AngularJS de llamar $ http se vería así:
$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 podría escribirse aún más simple usando métodos de acceso directo:
$http.post("http://example.appspot.com/rest/app", {"foo":"bar"}) .then(successCallback, errorCallback);
Hay varias cosas para notar:
success
y error
respectivamente (también tenga en cuenta los parámetros de cada callback) – Obsoleto en angular v1.5 then
función en su lugar. Lo anterior es solo un ejemplo rápido y algunos indicadores, asegúrese de revisar la documentación de AngularJS para obtener más información: http://docs.angularjs.org/api/ng.$http
Podemos implementar una solicitud jaja utilizando el servicio http en AngularJs, que ayuda a leer / cargar datos del servidor remoto.
Los métodos del servicio $ http se enumeran a continuación,
$http.get() $http.post() $http.delete() $http.head() $http.jsonp() $http.patch() $http.put()
Uno de los ejemplos:
$http.get("sample.php") .success(function(response) { $scope.getting = response.data; // response.data is an array }).error(){ // Error callback will trigger });
Puedes usar esto:
Descargar “angular-post-fix”: “^ 0.1.0”
A continuación, agregue ‘httpPostFix’ a sus dependencias mientras declara el módulo angular.
puede usar $ .param para asignar datos:
$http({ url: "http://example.appspot.com/rest/app", method: "POST", data: $.param({"foo":"bar"}) }).success(function(data, status, headers, config) { $scope.data = data; }).error(function(data, status, headers, config) { $scope.status = status; });
mira esto: AngularJS + ASP.NET Web API Cross-Domain Issue