我该如何在没有jQuery的情况下使用$http POST urlencoded表单数据?
我该如何在没有jQuery的情况下使用$http POST urlencoded表单数据?
我是AngularJS的新手,为了入门,我想使用AngularJS开发一个新的应用程序。
我试图使用我的Angular应用程序中的$http
向服务器端发起AJAX调用。
为了发送参数,我尝试了以下方法:
$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中的$.param
。为了减少对jQuery的依赖,我尝试了以下方法:
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会提供这个功能,但是怎么做呢?
仅使用 AngularJS 服务进行URL编码变量
从 AngularJS1.4开始,两个服务可以处理URL编码 POST 请求数据的过程,减少了使用transformRequest
或 JQuery 等外部依赖来处理数据的需要:
-
$httpParamSerializerJQLike
- 一个受 jQuery.param()
启发的序列化器(推荐) -
$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
的区别
通常,当处理复杂数据结构时,$httpParamSerializer
似乎使用了比 $httpParamSerializerJQLike
更少的“传统”URL编码格式。
例如(忽略括号的百分比编码):
• 编码数组
{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
我认为你需要做的是将数据从对象转换为URL参数而不是JSON字符串。
默认情况下,$http服务将通过将数据序列化为JSON并将其与内容类型“应用程序/JSON”一起发布来转换出站请求。当我们想要将值作为FORM提交时,我们需要更改序列化算法并使用内容类型“应用程序/ 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的新服务,请参见