Make AngularJS $http service behave like jQuery.ajax()
让ng的$http服务与jQuerr.ajax()一样易用
作者zeke
There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) don’t appear to be swappable with the jQuery equivalents (jQuery.post(), etc.) even though the respective manuals imply identical usage. That is, if your jQuery code looked like this before:
很多ng的初学者都有这样的困惑:为什么$http的service例如$http.post(),明明与jQuery的$.post()方法类似,却不可以直接换用,例如:
(function($) {
  jQuery.post('/endpoint', { foo: 'bar' }).success(function(response) {
    // ...
  });
})(jQuery);
You may find that the following doesn’t exactly work for you with AngularJS out of the box:
这样的代码在ng中并不会正常运行。
var MainCtrl = function($scope, $http) {
  $http.post('/endpoint', { foo: 'bar' }).success(function(response) {
    // ...
  });
};
The problem you may encounter is that your server does not appear to receive the { foo: 'bar' } params from the AngularJS request.
你会发现你的服务器并未收到{ foo: 'bar' } 的参数
 
The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively—that’s a darn shame because AngularJS is certainly not doing anything wrong. By default, jQuery transmits data usingContent-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
这个区别在于jQuery和ng在传输data时是否对其序列化。根本原因在于你的服务器无法解读ng传递过来的原始数据。jQ默认使用Content-Type: x-www-form-urlencoded 将data转码为foo=bar&baz=moe 的形式。ng则是Content-Type: application/json 来发送{ "foo": "bar", "baz": "moe" }  的JSON串,这使得服务器端(尤其是PHP)无法解读这样的数据。
Thankfully, the thoughtful AngularJS developers provided hooks into the $http service to let us impose x-www-form-urlencoded on all our transmissions. There are many solutions people have offered thus far on forums and StackOverflow, but they are not ideal because they require you to modify either your server code or your desired usage pattern of $http. Thus, I present to you the best possible solution, which requires you to change neither server nor client code but rather make some minor adjustments to $http‘s behavior in the config of your app’s AngularJS module:
好在周到的ng开发者们提供了$http的hooks使得我们可以强制以 x-www-form-urlencoded 发送数据,关于这点很多人提供了解决办法,但都不太理想,因为你不得不去修改你的服务器代码或者$http的代码。介于此,我给出了可能是最优的解决方案,前后端的代码均无需修改:
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;
  };
 
  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});
Do not use jQuery.param() in place of the above homegrown param() function; it will cause havoc when you try to use AngularJS $resourcebecause jQuery.param() will fire every method on the $resource class passed to it! (This is a feature of jQuery whereby function members of the object to parametrize are called and the return values are used as the parametrized values, but for our typical use case in AngularJS it is detrimental since we typically pass “real” object instances with methods, etc.)
不要使用jQuery.param()代替上面的原生param()方法,它将会造成ng的$resource方法无法使用。
Make AngularJS $http service behave like jQuery.ajax()
让ng的$http服务与jQuerr.ajax()一样易用
作者zeke
There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) don’t appear to be swappable with the jQuery equivalents (jQuery.post(), etc.) even though the respective manuals imply identical usage. That is, if your jQuery code looked like this before:
很多ng的初学者都有这样的困惑:为什么$http的service例如$http.post(),明明与jQuery的$.post()方法类似,却不可以直接换用,例如:
(function($) {
  jQuery.post('/endpoint', { foo: 'bar' }).success(function(response) {
    // ...
  });
})(jQuery);
You may find that the following doesn’t exactly work for you with AngularJS out of the box:
这样的代码在ng中并不会正常运行。
var MainCtrl = function($scope, $http) {
  $http.post('/endpoint', { foo: 'bar' }).success(function(response) {
    // ...
  });
};
The problem you may encounter is that your server does not appear to receive the { foo: 'bar' } params from the AngularJS request.
你会发现你的服务器并未收到{ foo: 'bar' } 的参数
 
The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively—that’s a darn shame because AngularJS is certainly not doing anything wrong. By default, jQuery transmits data usingContent-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
这个区别在于jQuery和ng在传输data时是否对其序列化。根本原因在于你的服务器无法解读ng传递过来的原始数据。jQ默认使用Content-Type: x-www-form-urlencoded 将data转码为foo=bar&baz=moe 的形式。ng则是Content-Type: application/json 来发送{ "foo": "bar", "baz": "moe" }  的JSON串,这使得服务器端(尤其是PHP)无法解读这样的数据。
Thankfully, the thoughtful AngularJS developers provided hooks into the $http service to let us impose x-www-form-urlencoded on all our transmissions. There are many solutions people have offered thus far on forums and StackOverflow, but they are not ideal because they require you to modify either your server code or your desired usage pattern of $http. Thus, I present to you the best possible solution, which requires you to change neither server nor client code but rather make some minor adjustments to $http‘s behavior in the config of your app’s AngularJS module:
好在周到的ng开发者们提供了$http的hooks使得我们可以强制以 x-www-form-urlencoded 发送数据,关于这点很多人提供了解决办法,但都不太理想,因为你不得不去修改你的服务器代码或者$http的代码。介于此,我给出了可能是最优的解决方案,前后端的代码均无需修改:
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;
  };
 
  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});
Do not use jQuery.param() in place of the above homegrown param() function; it will cause havoc when you try to use AngularJS $resourcebecause jQuery.param() will fire every method on the $resource class passed to it! (This is a feature of jQuery whereby function members of the object to parametrize are called and the return values are used as the parametrized values, but for our typical use case in AngularJS it is detrimental since we typically pass “real” object instances with methods, etc.)
不要使用jQuery.param()代替上面的原生param()方法,它将会造成ng的$resource方法无法使用。

翻译-让ng的$http服务与jQuerr.ajax()一样易用的更多相关文章

  1. [翻译]利用C#获取终端服务(Terminal Services)会话的闲置时间

    [翻译]利用C#获取终端服务(Terminal Services)会话的闲置时间 作者:Tuuzed(土仔)   发表于:2008年2月29日版权声明:可以任意转载,转载时请务必以超链接形式标明文章原 ...

  2. caffe官网的部分翻译及NG的教程

    Caffe原来叫:Convolutional Architecture for Fast Feature Embedding 官网的个人翻译:http://blog.csdn.net/fengbing ...

  3. ASP.NET实现二维码 ASP.Net上传文件 SQL基础语法 C# 动态创建数据库三(MySQL) Net Core 实现谷歌翻译ApI 免费版 C#发布和调试WebService ajax调用WebService实现数据库操作 C# 实体类转json数据过滤掉字段为null的字段

    ASP.NET实现二维码 using System;using System.Collections.Generic;using System.Drawing;using System.Linq;us ...

  4. jsp作为服务端,ajax请求回应

    刚学ajax,想以jsp作为服务端,来回应ajax的请求: 代码如下: <!DOCTYPE html> <html> <head lang="en"& ...

  5. 让AngularJS的$http 服务像jQuery.ajax()一样工作

    让AngularJS的$http 服务像jQuery.ajax()一样工作 $http的post . 请求默认的content-Type=application/json . 提交的是json对象的字 ...

  6. 在 vue cli3 的项目中配置双服务,模拟 ajax 分页请求

    最近安装了下vue cli3版本,与 cli 2 相比,文件少了,以前配置方法也不管用了.demo 中的大量的数据,需要做成 ajax 请求的方式来展示数据,因此,需要启动两个服务,一个用作前端请求, ...

  7. java 服务端解决ajax跨域问题

    //过滤器方式 可以更改为拦截器方式public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequ ...

  8. 使用javascript把图片转成base64位编码,然后传送到服务端(ajax调用的接口基于drupa7)

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  9. 【翻译】了解ASP.NET MVC中的Ajax助手

    原文:Understanding AJAX Helpers in ASP.NET MVC 作者: Shailendra Chauhan works as Software Analyst at rep ...

随机推荐

  1. 【索引】UML学习笔记

    行为图 交互图 交互概览图 时间图 顺序图 通信图 活动图 状态及图 用例图 结构图 包图 类图 对象图 组件图 部署图 组合结构图

  2. 三大跨平台网盘--google driver

    背景介绍 Google Drive,美国谷歌公司于2012年4月24日正式推出的一项云存储服务,可以向用户提供5GB的免费存储空间,同时还可以付费扩容. 准备工作 google帐号--帐号注册 软件- ...

  3. openstack kilo版本控制节点异常流量分析

  4. vim setting

    django_百度搜索 最近合并代码,发现文件缩进经常不一致,请大家把以下配置放到自己主目录下.vimrc文件中.   set tabstop=4   set shiftwidth=4   set e ...

  5. JVM中锁优化简介

    本文将简单介绍HotSpot虚拟机中用到的锁优化技术. 自旋锁 互斥同步对性能最大的影响是阻塞的实现,挂起线程和恢复线程的操作都需要转入内核态中完成,这些操作给系统的并发性能带来了很大的压力.而在很多 ...

  6. Google幻灯片

    本博文的主要内容有 .Google幻灯片的介绍 https://www.google.com/intl/zh-CN/slides/about/ 自行去注册Google账号,这里,不多赘述.

  7. Google生活

    本博文的主要内容有 .Google生活的介绍 1.Google生活的介绍 Google生活搜索的官网: http://shenghuo.google.cn/shenghuo/ http://sheng ...

  8. Oracle 监控索引使用

    Oracle提供一个监控索引的方法,来确定索引是否被使用.如果索引没有被使用,就可以删除它们以减少不必要的语句的开销.因为表上的大量不必要的索引可能会降低DML语句的性能,给数据库性能产生压力.所以生 ...

  9. 浅谈qmake之pro、pri、prf、prl文件

    浅谈qmake之pro.pri.prf.prl文件 转载自:http://blog.csdn.net/dbzhang800/article/details/6348432 尽管每次和cmake对比起来 ...

  10. in_array严格模式和普通模式的区别

    貌似是因为test转整型变0  0和0 匹配能成功 返回真 启用严格模式发现没有这个问题