如何在没有jQuery的情况下使用$http发布url编码的表单数据
How do I POST urlencoded form data with $http without jQuery?
我是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);
});
这是可行的,但它也在$.param
中使用jQuery。为了消除对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会提供这个功能,但是如何提供呢?
我认为您需要做的是将数据从对象转换为url参数,而不是JSON字符串。
来自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添加的新服务,请参阅
- 仅使用AngularJS服务的URL编码变量
仅使用AngularJS服务的URL编码变量
使用AngularJS 1.4及以上版本,两个服务可以处理POST请求的url编码数据过程,无需使用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
使用较少的";传统的";当涉及到复杂的数据结构时,url编码格式比CCD_。
例如(忽略括号的百分比编码(:
•编码阵列
{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
所有这些看起来都是过度使用(或不起作用(。。。只需这样做:
$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
`&password=${ encodeURIComponent(password) }` +
'&grant_type=password'
).success(function (data) {
问题是JSON字符串格式,您可以在数据中使用一个简单的URL字符串:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});
这是它应该的方式(请不要更改后端…当然不会…如果您的前端堆栈不支持application/x-www-form-urlencoded
,那么就把它扔掉…希望AngularJS支持!
$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
});
AngularJS 1.5 的魅力
各位,让我们给你一些建议:
在处理
$http
时使用promise.then(success, error)
,忘记.sucess
和.error
回调(因为它们已被弃用(从angularjs网站">您不能再使用JSON_CALLBACK字符串作为占位符来指定回调参数值的位置。">
如果你的数据模型比用户名和密码更复杂,你仍然可以这样做(如上所述(
$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
});
encodeURIComponent
的文档可以在此处找到
如果是表单,请尝试将标题更改为:
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
如果它不是一个表单和一个简单的json,那么试试这个头:
headers[ "Content-type" ] = "application/json";
从$http文档中,这应该可以工作。。
$http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(response) {
// your code...
});
$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);
});
var request = $http({
method: "post",
url: "process.cfm",
transformRequest: transformRequestAsFormPost,
data: { id: 4, name: "Kim" }
});
request.success(
function( data ) {
$scope.localData = data;
}
);
如果您有php作为后端,那么您将需要做更多的修改。。请检查此链接以修复php服务器端
虽然答案很晚,但我发现angular UrlSearchParams对我来说效果很好,它还可以处理参数的编码。
let params = new URLSearchParams();
params.set("abc", "def");
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http
.post(UrlUtil.getOptionSubmitUrl(parentSubcatId), params, options)
.catch();
这对我很有效。我使用angular作为前端,使用laravel-php作为后端。在我的项目中,angular web将json数据发送到laravel后端。
这是我的角度控制器。
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);
});
});
这是我的php后端laravel控制器。
public function httpTest(){
if (Input::has('username')) {
$user =Input::all();
return Response::json($user)->setCallback(Input::get('callback'));
}
}
这是我的laravel路由
Route::post('httpTest','HttpTestController@httpTest');
浏览器中的结果是
状态200
数据JSON_CALLBACK({"用户名":"Victoria","密码":"密码","回调":"JSON_CALLBACK"}(;js:18headers函数(c({a||(a=sc(b((;returnca[K(c(]||null:a}
有一个叫邮差的镀铬分机。您可以使用来测试后端url是否正常工作。https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
希望我的回答能对你有所帮助。
- HTML:从http到https发布表单
- 如何将AJAX POST转换为HTTP POST,以便在单击时发布
- 浏览器不发送 CORS HTTP 选项用于发布请求
- 使用Firefox的Javascript在iMacros中发布HTTP帖子
- 使用$http服务将数据发布到本地 json 文件时未发现错误
- $http发布呼叫选项而不是发布
- 使用 AngularJS Http Post 将表单 html 中的数据发布到服务器
- 如何使用 HTTP 发布在 ASPX 页中提交部分或全部控件
- 将标题授权设置为角度$http发布
- 如何从$http发布对象返回值
- 带有MVC的AngularJS,表格在http发布后不会刷新
- 在我的Node服务器上收到http发布请求时执行脚本
- angular$http发布带有标题的登录
- Angular$http发布到MVC操作,参数为null
- 流星:返回承诺's,然后再响应HTTP发布请求
- AngularJS$http发布对象包含数组的奇怪行为
- 如何在没有jQuery的情况下使用$http发布url编码的表单数据
- 在$http发布期间显示进度通知
- http发布,然后重定向到链接
- Http 发布图像在浏览器/瑞波模拟器中失败