- $http({
- method: "POST",
- url: "",
- data: id
- }).success();
- 发现发送的参数出现在了request payload里,参数为一个对象,于是查询了POST表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST请求如果不指定请求头RequestHeader,默认使用的Content-Type是text/plain;charset=UTF-8,在html中form的Content-type默认值:Content-type:application/x-www-form-urlencoded。
修改为
然后确实就转成form data了,但是参数如果是对象还是不行- $http({
- method: "POST",
- url: "",
- data: id,
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
- }).success();
于是再查资料发现,如果参数是对象,还需要加上transformRequest
这样终于可以了- $http({
- method: "POST",
- url: "",
- data: id,
- 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("&");
- }
- }).success();
其实仔细看transformRequest,也就是把参数转成序列化的形式,所以以后如果使用的话,干脆就写成序列化的形式就好了,省的还要再转一道。jquery中有$.param()方法可以实现,angularjs里面不知道有没有。
本文详细介绍了如何在AngularJS中正确地配置POST请求,包括设置Content-Type为application/x-www-form-urlencoded,并通过transformRequest处理对象参数,确保其正确序列化。
3万+

被折叠的 条评论
为什么被折叠?



