zoukankan      html  css  js  c++  java
  • AngularJS 学习笔记值post传值

    问题直接调用$http.post()方法时
    传值格式是这样的
    AngularJS <wbr>学习笔记值post传值
    php接收端接收到的是json格式的,怎么做的跟Ajax post那样传值呢?
     
    分析原因,angular的$http.post()方法默认数据传输格式是json的
          post: {'Content-Type': 'application/json;charset=utf-8'},
          put:  {'Content-Type': 'application/json;charset=utf-8'}
    所以要修改传输格式
     
    解决方法如下

    在angular模块中加入


    //修改post方式 form格式传值
    angular.module('MyModule', [], function($httpProvider) {//MyModule是你自己的app名称
      // Use x-www-form-urlencoded Content-Type
      $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
      $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
     
       
      var param = function(obj) {
        var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
          
        for(name in obj) {
          value = obj[name];
            
          if(value instanceof Array) {
            for(i=0; i
              subValue = value[i];
              fullSubName = name + '[' + i + ']';
              innerObj = {};
              innerObj[fullSubName] = subValue;
              query += param(innerObj) + '&';
            }
          }
          else if(value instanceof Object) {
            for(subName in value) {
              subValue = value[subName];
              fullSubName = name + '[' + subName + ']';
              innerObj = {};
              innerObj[fullSubName] = subValue;
              query += param(innerObj) + '&';
            }
          }
          else if(value !== undefined && value !== null)
            query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
        }
          
        return query.length ? query.substr(0, query.length - 1) : query;
      };
     
      // Override $http service's default transformRequest
      $httpProvider.defaults.transformRequest = [function(data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
      }];
    });
     
    结果如下
    AngularJS <wbr>学习笔记值post传值

     综上所述,问题就解决了。AngularJS <wbr>学习笔记值post传值
  • 相关阅读:
    努力努力,我假期要练琴学css
    在遇到困难时我们都会想要是这一切不曾发生该多好,可现实并不以我们的意志为转移,我们所能做的就是去克服...
    寒假学习目标~
    平安夜&&圣诞节
    you are the ont that we would like to trust and ca...
    Happy New Year!PR升3啦!
    呵呵,Merry Christmas & Happy New Year!
    使用Rx Framework实现XAML中的物体拖动
    MVVM绑定多层级数据到TreeView并设置项目展开
    Entity framework中EntityFunctions.CreateDateTime方法的闰年闰月bug
  • 原文地址:https://www.cnblogs.com/oxspirt/p/4761410.html
Copyright © 2011-2022 走看看