1、POST、GET携带参数的写法不一样,如下:
$http({method: 'post', url: './feedback/mail', data:{content:content,mailOrqq:mailOrqq,type:'chat-page-feedback'} }).success(function(data, status, headers, config) { console.log("IT部落是个神奇的网站"); }).error(function(data, status, headers, config){ console.error('我错了'); });
$http({method: 'GET',url:'./topic/getTopicCommentList', params:{topicId:$stateParams.topicId} }).success(function(data, status, headers, config) {}) .error(function(data, status, headers, config){});聪明的你一定看出来了,POST最好用Data携带数据、GET最好用params携带数据,两者使得区别如下描述:
- params – {Object.<string|Object>} – Map of strings or objects which will be serialized with theparamSerializer and appended as GET parameters.
- data – {string|Object} – Data to be sent as the request message data.
2、angularjs $http post参数后台无法接受问题
首先,我们需要了解http 请求携带参数的方式当Content-Type没有设置(即:Content-Type:text/plain;charset=UTF-8),http会以原始数据的方式携带数据,即:Request Payload ,
服务器端程序只能通过获取原始数据流的方式来进行解析请求数据;
表单提交(form data 携带数据)默认Content-Type:application/x-www-form-urlencoded,且数据是名值对的方式,所以服务器可以使用特定方式提取数据
通过以上描述你应该看出来了,angularjs $http post默认情况下Content-Type为text/plain;charset=UTF-8所以服务器端程序无法解析数据,所以有如下解法
解法如下:
$http({method: 'post', url: './feedback/mail', 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:{content:content,mailOrqq:mailOrqq,type:'chat-page-feedback'} }).success(function(data, status, headers, config) { console.log(data); }).error(function(data, status, headers, config){ console.error('获取聊天历史出错!'); });以上代码设置了Content-Type为text/plain;charset=UTF-8并且以键值对的方式传递数据,所以服务器端可以接受到参数
参考文献:
http://www.w2bc.com/Article/78730参考问答:
HTTP请求中的form data和request payload的区别?
1、HTTP请求过程中,get请求:表单参数以name=value&name1=value1的形式附到url的后面;
2、post请求:表单参数是在请求体中,也是name=value&name1=value1的形式在请求体中。
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
如果使用ajax请求,在请求头中出现 request payload导致参数的方式改变了 ,那么解决办法就是:
headers: {'Content-Type':'application/x-www-form-urlencoded'}
或者使用ajax设置:
$.ajaxSetup({contentType: 'application/x-www-form-urlencoded'});
这样,问题就可以解决。