• 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!

  • 相关阅读:
    面向对象编程听高翔“面向对象与生活”有感
    .Net调试技巧
    关于排序(简单)
    Http Handler由IIS6到IIS7的使用问题
    也谈【关于 京东员工被离职】另一个角度
    poj1062昂贵的聘礼
    poj1125 Stockbroker Grapevine
    poj1860 Currency Exchange
    poj1258 AgriNet
    poj2485 Highways
  • 原文地址:https://www.cnblogs.com/isuifeng/p/6012614.html
Copyright © 2020-2023  润新知