Javascript 在没有jQuery的情况下,如何使用$http发布URL编码的表单数据?
我是AngularJS新手,首先,我想只使用AngularJS开发一个新的应用程序 我正在尝试使用Angular应用程序中的Javascript 在没有jQuery的情况下,如何使用$http发布URL编码的表单数据?,javascript,jquery,angularjs,ajax,angularjs-http,Javascript,Jquery,Angularjs,Ajax,Angularjs Http,我是AngularJS新手,首先,我想只使用AngularJS开发一个新的应用程序 我正在尝试使用Angular应用程序中的$http对服务器端进行AJAX调用 为了发送参数,我尝试了以下方法: $http({ method: "post", url: URL, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: $.param({username: $scope.userNa
$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会提供此功能,但如何实现呢?从文档中可以看出,这应该是可行的
$http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(response) {
// your code...
});
如果是表单,请尝试将标题更改为:
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
如果不是表单和简单的json,请尝试以下标题:
headers[ "Content-type" ] = "application/json";
我认为您需要做的是将数据从对象转换为url参数,而不是转换为JSON字符串 默认情况下,$http服务将通过以下方式转换传出请求: 将数据序列化为JSON,然后将其与内容一起发布- 键入“application/json”。当我们想将值作为表单发布时 post,我们需要更改序列化算法并发布数据 内容类型为“application/x-www-form-urlencoded” 例如 更新 要使用AngularJS V1.4中添加的新服务,请参阅
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作为前端,使用laravel php作为后端。在我的项目中,AngularWeb将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);
});
});
public function httpTest(){
if (Input::has('username')) {
$user =Input::all();
return Response::json($user)->setCallback(Input::get('callback'));
}
}
这是我的php后端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);
});
});
public function httpTest(){
if (Input::has('username')) {
$user =Input::all();
return Response::json($user)->setCallback(Input::get('callback'));
}
}
这是我的拉威尔路线
Route::post('httpTest','HttpTestController@httpTest');
浏览器中的结果是
状态200数据JSON_回调({“用户名”:“维多利亚”,“密码”:“密码”,“回调”:“JSON_回调”}); js:18头函数(c){a | |(a=sc(b));返回 c?a[K(c)]| | null:a} 有一个叫做邮递员的chrome分机。您可以使用测试后端url是否正常工作。
希望我的回答能对你有所帮助。所有这些看起来都有些过火(或者不起作用)。。。只要这样做:
$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
`&password=${ encodeURIComponent(password) }` +
'&grant_type=password'
).success(function (data) {
仅使用AngularJS服务的URL编码变量
使用AngularJS 1.4及更高版本,两个服务可以处理POST请求的url编码数据过程,无需使用transformRequest
或使用外部依赖项(如jQuery)操作数据:
带有$http.post()的示例
$httpParamSerializerJQLike
和$httpParamSerializer
有何不同
一般来说,对于复杂的数据结构,$httpParamSerializer
使用的“传统”url编码格式似乎比$httpParamSerializerJQLike
少
例如(忽略括号的百分比编码):
•对数组进行编码
{sites:['google', 'Facebook']} // Object with array property
sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike
sites=google&sites=facebook // Result with $httpParamSerializer
•对对象进行编码
$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
{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
问题在于JSON字符串格式,您可以在数据中使用简单的URL字符串:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});
虽然回答晚了,但我发现Argular 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();
这里是它应该的方式(请不要更改后端…当然不是…如果您的前堆栈不支持
应用程序/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
和.success
回调(因为它们被弃用).error
- 从angularjs站点“您不能再使用JSON_回调字符串作为占位符来指定回调参数值的位置。”
可以找到
encodeURIComponent
的文档我不知道实际的问题是什么,但是您是否尝试了$http({method:'post',url:url,data:{username:$scope.username,password:$scope.password}});
您的第一个方法应该可以工作,是$scope.userName
定义的吗?为什么不尝试数据:数据
?@KevinB:sorry..我已经做了正确的编辑。@mritunjay:sorry..我已经做了编辑..我也在尝试同样的方法。@Veer成功了还是您仍然有问题?@Kevin我不确定这一点,但是..有一次我尝试发送strin它给了我一个error@KevinB很好..我明白了..我认为在发送字符串时需要更改标题..请注意,发送正确的标题
不会影响数据
,这些数据仍然需要URL编码,不管怎样。数据仍然以json格式发送。您必须将数据编码为x-www-form-urlencoded adding标头没有收到任何内容。我仍然收到空白的$\u POST
数组!这是控制器中的$http调用吗?还有一件事是服务器端php?我找到了解决方案,你仍然遇到问题@Veer吗?感谢你没有使用JQuery!如果我需要提交多部分/表单数据呢?只要有必要将jqLite置于angular.element
下,您只需返回angular.element.param(obj);
@Vicary请记住,param()不是在jqLite中实现的-这是另一种方法var obj={a:1,b:2};Object.keys(obj).reduce(函数(p,c){
$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
});
$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);
});