zoukankan      html  css  js  c++  java
  • 让AngularJS的$http 服务像jQuery.ajax()一样工作

    先比较下他们的差别

    1. $http的post
      . 请求默认的content-Type=application/json
      . 提交的是json对象的字符串化数据,
      . 后端无法从post中获取,
      . 跨域请求是复杂请求,会发送OPTIONS的验证请求,成功后才真正发起post请求

    2. jQuery.post
      . 使用的是content-Type=application/x-www-form-urlencoded -
      . 提交的是form data,
      . 后端可以从post中获取,
      . 简单跨域请求,直接发送

    解决办法有两个:

    1. 是后端支持复杂的跨域请求
    那么后端就需要设置如下的信息

        def options(self):
            self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
            self.set_header('Access-Control-Max-Age', 86400)
            self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
            self.write('')
    

    后端post中拿不到数据,我们需要自己处理request的body,看看python和php的处理方式:
    python

    #这种写法支持多种content-Type提交
        def POST(self):
            if self.request.headers['Content-Type'].find('application/json') >= 0:
                body = self.request.body
                if body:
                    return json.loads(body.decode())
                else:
                    return {}                
            else:    
                paras = {}
                for k, v in self.request.body_arguments.items():
                    paras[k] = v[-1].decode()
                return paras
    

    php

    <?
    $params = json_decode(file_get_contents('php://input'));
    ?>
    

    2. 配置AngularJS
    配置$http服务的默认content-Type=application/x-www-form-urlencoded,如果是指配置这个的话,虽然提交的content-Type改了,但是提交的数据依然是个json字符串,不是我们想要的form data形式的键值对,需要实现param方法. Talk is cheap, i show you the code.

    angular.module('MyModule', [], function($httpProvider) {
        // Use x-www-form-urlencoded Content-Type
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    
        /**
         * The workhorse; converts an object to x-www-form-urlencoded serialization.
         * @param {Object} obj
         * @return {String}
         */
        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 < value.length; ++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;
        };
    
        //一个function数组,负责将请求的body,也就是post data,转换成想要的形式
        // Override $http service's default transformRequest    
        $httpProvider.defaults.transformRequest = [function(data) {
            return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
        }];
    });
    
    

    配合一点$resource的API参考,这个代码就好懂了:
    https://docs.angularjs.org/api/ngResource/service/$resource

    Note:
    上述param方法定义的地方不要使用jQuery.param方法,因为jQuery.param方法会将要处理的对象上的function全执行一边,把返回的值当做参数的值,这是我们不期望的,我们写的这个param方法也是为了解决上面说的content-Type=x-www-form-urlencoded,但是提交的数据依然是json串的问题。

    如果不使用$resource,还有一种方法

            $scope.formData = {};
            $http({
                    method: 'POST',
                    url: '/user/',
                    data: $.param($scope.formData), // pass in data as strings
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
                })
                .success(function(data) {
                    console.log(data);
    
                    if (!data.success) {
                        // if not successful, bind errors to error variables
                        $scope.errorName = data.errors.name;
                        $scope.errorSuperhero = data.errors.superheroAlias;
                    } else {
                        // if successful, bind success message to message
                        $scope.message = data.message;
                    }
                });
    

    参考
    http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

  • 相关阅读:
    strtok() and strtod()
    quernation,euler,rotationmatrix之间的相互转换
    Ubuntu16.04+Ros+Usb_Cam ORB SLAM2
    windows10下VS2013搭建opencv2.4.9吐血之作
    深度学习之numpy.poly1d()函数
    matplotlib动态图subplots()和subplot()不同及参数
    python学习之matplotlib绘制动图(FuncAnimation()参数)
    javascipt——jQuery
    Javascript——(2)DOM
    linux nc 命令详解
  • 原文地址:https://www.cnblogs.com/wancy86/p/5855475.html
Copyright © 2011-2022 走看看