翻译-让ng的$http服务与jQuerr.ajax()一样易用
2016-09-25 19:53
204 查看
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
很多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' } 的参数
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 using
这个区别在于jQuery和ng在传输data时是否对其序列化。根本原因在于你的服务器无法解读ng传递过来的原始数据。jQ默认使用
Thankfully, the thoughtful AngularJS developers provided hooks into the
好在周到的ng开发者们提供了$http的hooks使得我们可以强制以
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()代替上面的原生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
很多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' } 的参数
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 using
这个区别在于jQuery和ng在传输data时是否对其序列化。根本原因在于你的服务器无法解读ng传递过来的原始数据。jQ默认使用
Thankfully, the thoughtful AngularJS developers provided hooks into the
好在周到的ng开发者们提供了$http的hooks使得我们可以强制以
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()代替上面的原生param()方法,它将会造成ng的$resource方法无法使用。
让ng的$http服务与jQuerr.ajax()一样易用
作者zeke
There is much confusion among newcomers to AngularJS as to why the
$httpservice 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 using
Content-Type: x-www-form-urlencodedand the familiar
foo=bar&baz=moeserialization. AngularJS, however, transmits data using
Content-Type: application/jsonand
{ "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
$httpservice to let us impose
x-www-form-urlencodedon 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
$resourceclass 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
$httpservice 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 using
Content-Type: x-www-form-urlencodedand the familiar
foo=bar&baz=moeserialization. AngularJS, however, transmits data using
Content-Type: application/jsonand
{ "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
$httpservice to let us impose
x-www-form-urlencodedon 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
$resourceclass 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方法无法使用。
相关文章推荐
- 让AngularJS的$http 服务像jQuery.ajax()一样工作
- AngularJs初探--让AngularJS的$http 服务像jQuery.ajax()一样工作
- 第五章 HTTP客户端服务 --httpclient4 中文版帮助文档,最新官方版翻译版(五)
- 【转】第五章 HTTP客户端服务 --httpclient4 中文版帮助文档,最新官方版翻译版
- [翻译]AJAX XMLHttpRequest对象 详解
- Ajax实现的bing 翻译接口 像词典一样
- http服务&ajax编程
- 实现jquery.ajax及原生的XMLHttpRequest跨域调用WCF服务的方法
- Angularjs学习笔记——Ajax服务(跨域)&&ng路由
- drupal7安装时出错 导入翻译出错 的新原因及解决办法 An AJAX HTTP error occurred
- 实现jquery.ajax及原生的XMLHttpRequest调用WCF服务的方法
- 了解HTTP服务&Ajax编程
- 把Angular中的$http变成jQuery.ajax()一样,可以让后台(php)轻松接收到参数
- 关于”System.ServiceModel.Activation.WebServiceHostFactory“与"<webHttp/>"以及RestFul/启用了Ajax的WCF服务
- drupal7 导入翻译出错 An AJAX HTTP error occurred
- 实现jquery.ajax及原生的XMLHttpRequest调用WCF服务的方法
- Web服务最佳实践(翻译)
- Fixing AJAX: XMLHttpRequest
- [翻译]Ajax原则(Ajax Principles)
- 翻译:2006互联网网站 or 服务的流行元素