Angular与PHP之间的不同的请求方式,post/get导致的传参问题

angularJS的$http发送POST请求,PHP无法接受数据的问题

使用jQuery进行ajax请求

  $.ajax({
   type: 'POST',
   url:'url.php',
   data: data,
   dataType: 'json',
   success: function(res){
       //do something
   }
 });

对这个传输的数据我们一般会直接使用serialize()处理后再传输,但在发送post请求时jquery会把这个对象转换为字符串后再发送,类似"tel=1233&pass=12434"

而AngularJs默认的请求头是application/json,传输的是一个Json数据而不是一个转换后的字符串,在php端接收的时候不能直接使用$_POST方式接收.这样是获取不到数据的.

$POST方式只能接收Content-Type: application/x-www-form-urlencoded提交的数据,也就是表单提交的数据

解决方案

1.引用JQuery,使用JQuery的$.param()方法序列化参数后传递

$http({
     method  : 'POST',
     url: 'process.php',
     data: $.param($scope.formData), //序列化参数
     headers: { 'Content-Type': 'application/x-www-form-urlencoded' } )
})  

2.使用file_get_contents("php://input")获取再处理

$input = file_get_contents("php://input",true);
echo $input;