当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngularJS $http post 传递参数数据的方法

AngularJS $http post 传递参数数据的方法

2019年05月28日  | 移动技术网IT编程  | 我要评论

在cordova开发的时候使用到了$http的post方法,传递的参数服务端怎么都接收不到,搜索了下,发现使用angularjs通过post传递参数还是需要设置一些东西才可以!

1、不能直接使用params

例如:

$http({    
method: "post",    
url: "http://192.168.2.2:8080/setid",    
params: { 
cellphoneid: "b373fed6be325f7"}  
}).success();

当你这样写的时候它会把id写到url后面:

http://192.168.2.2:8080/setid?cellphoneid=b373fed6be325f7"

会在url后面添加"?cellphoneid=b373fed6be325f7",查了些资料发现params这个参数是用在get请求中的,而post/put/patch就需要使用data来传递;

2、直接使用data

$http({ 
   method: "post", 
   url: "http://192.168.2.2:8080/setid", 
   data: {
 cellphoneid: "b373fed6be325f7"
} }).success();

这样的话传递的,是存在于request payload中,后端无法获取到参数

angularjs $http post

这时发现content-type:application/json;charset=utf-8,而post表单请求提交时,使用的content-type是application/x-www-form-urlencoded,所以需要把content-type修改下!

3、修改content-type

$http({ 
   method: "post", 
   url: "http://192.168.2.2:8080/setid", 
   data: {cellphoneid: "b373fed6be325f7"},
  headers: { 'content-type': 'application/x-www-form-urlencoded' }
 }).success();

angularjs $http post

这时数据是放到了form data中但是发现是以对象的形式存在,所以需要进行序列化!

4、对参数进行序列化

$http({ 
   method: "post", 
   url: "http://192.168.2.2:8080/setid", 
   data: {cellphoneid: "b373fed6be325f7"}, 
  headers: { 'content-type': 'application/x-www-form-urlencoded' }, 
    transformrequest: function(obj) { 
   var str = []; 
   for (var s in obj) { 
   str.push(encodeuricomponent(s) + "=" + encodeuricomponent(obj[s])); 
   } 
   return str.join("&"); 
  } 
 }).success(); 

以上这篇angularjs $http post 传递参数数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网