angular.js的post数据方式

  公司的项目前端部分现在改用angular,一切从头学起,今天记录一下关于数据请求的问题,由于get的请求方式比较简单,与post也类似,所以就单独讲讲post方式。

  文档上post数据的写法有好几种,都是利用$http模块,通用写法如下:

// Simple GET request example:
$http({
    method: 'GET',
    url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

  然后我们将方式改为post,加上data试一下。

$http({  
    method:'post',  
    url:'test.php',
    data:{name:'test',age:20},  
}).then(function successCallback(response) {
    alert('添加成功');    
}, function errorCallback(response) {
    alert('添加失败');
});

  php文件中我们就写一行print_r($_POST)即可。

  打开谷歌浏览器F12,查看下调试信息,发现数据传输过去了

  但是细心的朋友一定会发现一个问题,就是我们这里的传输方式是request playload,而不是我们通常的form data。他俩最大的区别就是,request playload的方式我们在php文件中通过$_POST是拿不到传过来的数据的。可以看到返回的打印信息为空。

  

  我们再修改一下,加上headers和transformRequest

$http({  
    method:'post',  
    url:'test.php',
    data:{name:'test',age:20},  
    headers:{'Content-Type': 'application/x-www-form-urlencoded'},    
    transformRequest: function (data) {
      return $.param(data);
    }
}).then(function successCallback(response) {
    alert('添加成功');    
}, function errorCallback(response) {
    alert('添加失败');
});

  然后查看返回值

  成功了,并且此时传输方式变成了

  OK,over!

转载于:https://www.cnblogs.com/isuifeng/p/6012614.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值