翻译-让ng的$http服务与jQuerr.ajax()一样易用

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方法无法使用。

时间: 2024-10-27 04:14:12

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

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

[翻译]利用C#获取终端服务(Terminal Services)会话的闲置时间 作者:Tuuzed(土仔)   发表于:2008年2月29日版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明.http://www.cppblog.com/tuuzed/archive/2008/02/29/43424.html 原著:Guy Teverovsky 翻译:土仔Tuuzed原文出处:Querying TS session idle time with C#原文URL:

野兽的Angular Api 学习、翻译及理解 - - $compile编译服务与指令

野兽的ng api学习 -- $compile $compile 这是个编译服务.编译一段HTML字符串或者DOM的模板, 产生一个将scope和模板连接到一起的函数. 编译服务主要是和指令为指令服务,下面的文章也是主要介绍指令的. 下面是一个被声明的带指令定义对象的指令的示例: var myModule = angular.module(...); myModule.directive('directiveName', [“injectables”,…,function factory(inj

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

Caffe原来叫:Convolutional Architecture for Fast Feature Embedding 官网的个人翻译:http://blog.csdn.net/fengbingchun/article/details/49535873 NG的英文教程:http://ufldl.stanford.edu/tutorial/supervised/MultiLayerNeuralNetworks/ NG的中文教程:http://ufldl.stanford.edu/wiki/i

ros wiki翻译之创建消息和服务

描述:本教程介绍如何创建和构建msg和srv文件以及rosmsg,rossrv和roscp命令行工具. 1 msg和srv简介 msg:msg文件是描述ROS消息字段的简单文本文件.它们用于为不同语言(c++或者python等)的消息生成源代码. srv:srv文件用来描述服务.它由两部分组成:请求(request)和响应(response). msg文件存储在包的msg目录中,而srv文件存储在srv目录中. msg只是简单的文本文件,每行有一个字段类型和字段名称.您可以使用的字段类型有(如同

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

刚学ajax,想以jsp作为服务端,来回应ajax的请求: 代码如下: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="../js/jquery.min.js" ></script> <script type=&

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

<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src='http://code.jquery.com/jquery-1.9.1.min.js'></script> <script src='jquery.base64.js'><

java 服务端解决ajax跨域问题

//过滤器方式 可以更改为拦截器方式public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; resp

ng自定义服务(利用factory)

ng中我们可以自己定义自己的服务,服务中是一些使用重复率较高的方法.因此有效的使用服务可以提高开发速度. ng中定义服务的方法有多种,service,factory,provide,在此我只介绍最长用的一种,利用factory factory会以返回一个对象的形式 app.factory("服务的名字",[function(){ return{ getName:function(){ /........./ } } }]); demo: services/zct_get_my_righ

Angularjs[13] - 定义服务 $provide 中 provider 方法

服务本身是一个任意的对象,ng提供的服务过程涉及它的依赖注入机制. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div ng-app="myApp"> <div ng-controller=