HTTP POST using Angular.js

后端 未结 3 1651
眼角桃花
眼角桃花 2020-12-14 02:21

I\'m new to the scene and I want to use Angular.js to make an HTTP POST request. I\'m accessing PHP scripts which have parameters that are just POST variables. What gets ret

3条回答
  •  忘掉有多难
    2020-12-14 03:02

    Rather old post... but I figure my solution might come in handy for others as well.

    I did not like the

    json_decode(file_get_contents("php://input"));
    

    solution... Basically because it seems against good practice (I might be wrong on this)

    This is how I got it solved (adapted to the example above)

    function PhpCtrl($scope, $http, $templateCache) {
      var method = 'POST';
      var url = 'url.php';
      $scope.codeStatus = "";
      $scope.add = function() {
        var FormData = {
          'name' : document.f1.name.value,
          'password' : document.f1.password.value
        };
        $http({
          method: method,
          url: url,
          data: $.param({'data' : FormData}),
          headers: {'Content-Type': 'application/x-www-form-urlencoded'},
          cache: $templateCache
        }).
        success(function(response) {
            $scope.codeStatus = response.data;
        }).
        error(function(response) {
            $scope.codeStatus = response || "Request failed";
        });
        return false;
      };
    }
    

    once this done

    data: $.param({'data' : FormData}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    

    you can access the data you normally would in PHP

    $data = $_POST['data'];
    

提交回复
热议问题