如何在没有jQuery的情况下用$http POST urlencoded表单数据?

我是AngularJS的新手,首先,我想只使用AngularJS开发一个新的应用程序。

我正在尝试使用我的Angular应用程序对服务器端进行AJAX调用。$http

为了发送参数,我尝试了以下操作:

$http({
    method: "post",
    url: URL,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
    console.log(result);
});

这是有效的,但它也在使用jQuery。为了删除对jQuery的依赖性,我尝试了:$.param

data: {username: $scope.userName, password: $scope.password}

但这似乎失败了。然后我试过了:params

params: {username: $scope.userName, password: $scope.password}

但这似乎也失败了。然后我试过了:JSON.stringify

data: JSON.stringify({username: $scope.userName, password: $scope.password})

我找到了这些可能的答案,但没有成功。我做错了什么吗?我敢肯定,AngularJS会提供这个功能,但是如何呢?


答案 1

我认为您需要做的是将数据从对象转换为JSON字符串,而是转换为url参数。

来自Ben Nadel的博客

默认情况下,$http服务将通过将数据序列化为 JSON,然后使用内容类型“application/json”发布来转换传出请求。当我们想将值作为 FORM post 发布时,我们需要更改序列化算法,并使用内容类型“application/x-www-form-urlencoded”发布数据。

示例来自此处

$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 () {});

更新

要使用 AngularJS V1.4 中添加的新服务,请参阅


答案 2

仅使用 AngularJS 服务的 URL 编码变量

使用AngularJS 1.4及更高版本,两个服务可以处理POST请求的url编码数据的过程,从而无需使用或使用jQuery等外部依赖项来操作数据:transformRequest

  1. $httpParamSerializerJQLike - 受jQuery的.param()启发的序列化程序(推荐))

  2. $httpParamSerializer - Angular 本身用于 GET 请求的序列化程序

$http() 的示例

$http({
  url: 'some/api/endpoint',
  method: 'POST',
  data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
  }
}).then(function(response) { /* do something here */ });

观看更详细的 Plunker 演示


使用 $http.post() 的示例

$http.post(
    'some/api/endpoint',
    data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
    {
       headers: {
         'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
      }
    }
).then(function

如何和不同$httpParamSerializerJQLike$httpParamSerializer

一般来说,它似乎使用比复杂数据结构更“传统”的url编码格式。$httpParamSerializer$httpParamSerializerJQLike

例如(忽略括号的百分比编码):

对数组进行编码

{sites:['google', 'Facebook']} // Object with array property

sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike

sites=google&sites=facebook // Result with $httpParamSerializer

对对象进行编码

{address: {city: 'LA', country: 'USA'}} // Object with object property

address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike

address={"city": "LA", country: "USA"} // Result with $httpParamSerializer