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

后端 未结 11 2506
生来不讨喜
生来不讨喜 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:07

    I think you need to do is to transform your data from object not to JSON string, but to url params.

    From Ben Nadel's blog.

    By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

    Example from here.

    $http({
        method: 'POST',
        url: url,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(obj) {
            var str = [];
            for(var p in obj)
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            return str.join("&");
        },
        data: {username: $scope.userName, password: $scope.password}
    }).then(function () {});
    

    UPDATE

    To use new services added with AngularJS V1.4, see

    • URL-encoding variables using only AngularJS services

提交回复
热议问题