angularjs 有本身封装的 ajax 服务 $http,因为用惯了 jQuery 的 ajax,所以,自己封装了一下 angularjs 的 $http,代码如下
- app.factory('dataFactory', function ($http, $q){
- var factory = {};
- factory.getlist = function(endpoint, method, headers, params) {
- var defer = $q.defer();
- if (method == 'GET') {
- $http({
- url: endpoint,
- method: "GET",
- headers: headers,
- params: params,
- }).success(function (data) {
- defer.resolve(data);
- }).
- error(function (data, status, headers, config) {
- // defer.resolve(data);
- defer.reject(data);
- });
- } else {
- $http({
- url: endpoint,
- method: method,
- headers: headers,
- data: params,
- }).success(function (data) {
- defer.resolve(data);
- }).
- error(function (data, status, headers, config) {
- // defer.resolve(data);
- defer.reject(data);
- });
- }
- return defer.promise;
- };
- return factory;
- });
在 controller 中引入 dataFactory 和 $http 即可使用更方便的调用 ajax, 一般情况下 headers 为
- headers = {
- 'Content-Type': 'application/json'
- };
params 为一个 json 字符串
然后调用
- dataFactory.getlist("/api/checkDuplicate", 'GET', headers, params).then(function(data) {
- //success函数
- },
- function(data) {
- //error函数
- })
但是其中又一次在项目中,后台框架使用的是 Struts 框架,在一个 Python 中使用的很好的 dataFactory,在这里的后台取不到数,最后发现是应为 header 设置不对,而且 params 的格式也不正确,可以把 header 修改为
- headers = {
- 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
- };
上面 dataFactory 中 else 添加转换 params 代码:
- 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;
- };
- $http({
- url: endpoint,
- method: method,
- headers: headers,
- data: param(params),
- }).success(function (data) {
- defer.resolve(data);
- }).
- error(function (data, status, headers, config) {
- // defer.resolve(data);
- defer.reject(data);
- });
只是个人觉得这个方式比较方便,记录下来,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
来源: http://www.jb51.net/article/114030.htm