问题描述
我是AngularJS的新手,一开始,我想只使用AngularJS开发一个新的应用程序。
I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.
我正在尝试对其进行AJAX调用服务器端,从我的Angular App使用 $ http
。
I am trying to make an AJAX call to the server side, using $http
from my Angular App.
为了发送参数,我尝试了以下方法: / p>
For sending the parameters, I tried the following:
$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);
});
这是有效的,但它也在 $。param中使用jQuery
。为了消除对jQuery的依赖,我尝试了:
This is working, but it is using jQuery as well at $.param
. For removing the dependency on jQuery, I tried:
data: {username: $scope.userName, password: $scope.password}
但这似乎失败了。然后我尝试 params
:
but this seemed to fail. Then I tried params
:
params: {username: $scope.userName, password: $scope.password}
但这似乎也失败了。然后我尝试了 JSON.stringify
:
but this also seemed to fail. Then I tried JSON.stringify
:
data: JSON.stringify({username: $scope.userName, password: $scope.password})
我找到了这些可能的答案我的追求,但没有成功。难道我做错了什么?我确信,AngularJS会提供这个功能,但是如何?
I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong? I am sure, AngularJS would provide this functionality, but how?
推荐答案
我认为你需要做的是转换你的数据对象不是JSON字符串,而是url params。
I think you need to do is to transform your data from object not to JSON string, but to url params.
。
示例。
$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,参见
UPDATE
To use new services added with AngularJS V1.4, see
- URL-encoding variables using only AngularJS services
这篇关于如何在没有jQuery的情况下使用$ http发布urlencoded表单数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!