Request AJAX post with angularjs

4

Hello,

I wanted to know how I make a POST request for a url with angularJS and also wanted to know how I transform a normal javascript object into a json, to send in that request.

    
asked by anonymous 14.02.2015 / 07:04

2 answers

4

You can use the AngularJS $http service.

  • In your controller, declare the dependency of the service $http :

    .controller('TesteCtrl', ['$scope', '$http', function($scope, $http){ ...
    
  • Your javascript object ( jsonObj in this example) can be sent directly. The Angular will automatically serialize before sending it:

    var jsonObj = { campo1: "teste", campo2 : 123 };
    
    $http.post('/url-da-requisicao', jsonObj)
    .success(function(data, status, headers, config) {
      // sucesso! 
      // data agora contém o que foi retornado pelo servidor
      })
    .error(function(data, status, headers, config) {
      // erro!
      // você pode verificar o parâmetro "status" para ver o código HTTP do erro
    });
    
  • Note: By default, the% w of% of the post used by the angle is Content-type . If your server is using PHP, you will not be able to directly read the data received in JSON. Here's a solution.

        
    14.02.2015 / 17:43
    4

    In AngularJS you can send AJAX requests in several ways:

    • AJAX calls via the $ http service.
    • JSONP calls via the $ http service.
    • REST type calls.

    AngularJS & JSONP

    Example of a JSONP call with the url set:

    var url = http://jenkov.com/theService.json?callback=JSON_CALLBACK "; 
    var responsePromise = $ http.jsonp (url, 
                 {params: { 
                       p1: "v1" 
                      ,p2: "v2" 
                    } 
                  } 
                ); 
    
    responsePromise.success (function (data) { 
        // faz alguma coisa com o objeto JavaScript
        // (no parâmetro "data"). 
    });
    

    Study: link $ http

        
    14.02.2015 / 16:54