How do I POST urlencoded form data with $http without jQuery?

后端 未结 11 2376
生来不讨喜
生来不讨喜 2020-11-21 23:27

I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.

I am trying to make an AJAX call to the server side, using

相关标签:
11条回答
  • 2020-11-22 00:24

    you need to post plain javascript object, nothing else

               var request = $http({
                    method: "post",
                    url: "process.cfm",
                    transformRequest: transformRequestAsFormPost,
                    data: { id: 4, name: "Kim" }
                });
    
                request.success(
                    function( data ) {
                        $scope.localData = data;
                    }
                );
    

    if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side

    0 讨论(0)
  • 2020-11-22 00:25

    This worked for me. I use angular for front-end and laravel php for back-end. In my project, angular web sends json data to laravel back-end.

    This is my angular controller.

    var angularJsApp= angular.module('angularJsApp',[]);
    angularJsApp.controller('MainCtrl', function ($scope ,$http) {
    
        $scope.userName ="Victoria";
        $scope.password ="password"
    
    
           $http({
                method :'POST',
                url:'http://api.mywebsite.com.localhost/httpTest?callback=JSON_CALLBACK',
                data: { username :  $scope.userName , password: $scope.password},
                headers: {'Content-Type': 'application/json'}
            }).success(function (data, status, headers, config) {
                console.log('status',status);
                console.log('data',status);
                console.log('headers',status);
            });
    
    });
    

    This is my php back-end laravel controller.

    public function httpTest(){
            if (Input::has('username')) {
                $user =Input::all();
                return  Response::json($user)->setCallback(Input::get('callback'));
            }
        }
    

    This is my laravel routing

    Route::post('httpTest','HttpTestController@httpTest');
    

    The result in browser is

    status 200
    data JSON_CALLBACK({"username":"Victoria","password":"password","callback":"JSON_CALLBACK"}); httpTesting.js:18 headers function (c){a||(a=sc(b));return c?a[K(c)]||null:a}

    There is chrome extension called postman. You can use to test your back-end url whether it is working or not. https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en

    hopefully, my answer will help you.

    0 讨论(0)
  • 2020-11-22 00:27

    Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support application/x-www-form-urlencoded, then throw it away ... hopefully AngularJS does !

    $http({
         method: 'POST',
         url: 'api_endpoint',
         headers: {'Content-Type': 'application/x-www-form-urlencoded'},
         data: 'username='+$scope.username+'&password='+$scope.password
     }).then(function(response) {
        // on success
     }, function(response) {
        // on error
     });
    

    Works like a charm with AngularJS 1.5

    People, let give u some advice:

    • use promises .then(success, error) when dealing with $http, forget about .sucess and .error callbacks (as they are being deprecated)

    • From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."

    If your data model is more complex that just a username and a password, you can still do that (as suggested above)

    $http({
         method: 'POST',
         url: 'api_endpoint',
         headers: {'Content-Type': 'application/x-www-form-urlencoded'},
         data: json_formatted_data,
         transformRequest: function(data, headers) {
              return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
         }
    }).then(function(response) {
      // on succes
    }, function(response) {
      // on error
    });
    

    Document for the encodeURIComponent can be found here

    0 讨论(0)
  • 2020-11-22 00:28

    All of these look like overkill (or don't work)... just do this:

    $http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
                         `&password=${ encodeURIComponent(password) }` +
                         '&grant_type=password'
    ).success(function (data) {
    
    0 讨论(0)
  • 2020-11-22 00:29
    $http({
    
        method: "POST",
        url: "/server.php",
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: "name='Олег'&age='28'",
    
    
    }).success(function(data, status) {
        console.log(data);
        console.log(status);
    });
    
    0 讨论(0)
提交回复
热议问题