我有一个后端,它以jQuery的$.param返回的格式理解查询字符串.例如,有一个像这样的对象
{ search: "Miller",name: ["Felipe","Fernanda"] }
将使用以下查询字符串请求URL:
http://theurl/path?search=Miller&name%5B%5D=Felipe&name%5B%5D=Fernanda
基本上它使用名称[] = Felipe& name [] = Fernada,但URL编码.
当AngularJS解析时,同一个对象最终会使用以下格式:
http://theurl/path?search=Miller&name=Felipe,Fernanda
哪个我的后端不明白.
阅读this other question,我认为使用transformRequest会有所帮助,但事实并非如此.这是我的测试代码:
HTML
<div ng-controller="UserCtrl"> <pre>{{ data | json}}</pre> </div>
JavaScript的
var myApp = angular.module('myApp',['ngResource']); var transformFn = function(data,headersGetter) { console.debug('transformRequest',data); if (!data) return; console.debug('data in',data); var dataOut = $.param(data); console.debug('data out',dataOut); return dataOut; }; myApp.config(['$httpProvider',function($httpProvider) { $httpProvider.defaults.transformRequest.push(transformFn); }]); myApp.factory('User',['$resource',function($resource) { return $resource('/echo/:type/',{type:'json'},{ query: { method: 'GET' } }); }]); myApp.controller('UserCtrl',['$scope','User',function($scope,User) { User.query({ seach: 'Miller',name: ['Felipe','Fernanda']},function(data) { console.debug('data',data); $scope.data = data; }); }]);
但是,当您尝试运行此代码时,您会注意到transformFn上的data属性始终未定义,并且查询字符串保持AngularJS格式.
你也可以在jsFiddle中看到这个:http://jsfiddle.net/fcoury/QKmnX/
知道如何强制查询字符串使用jQuery的$.param格式吗?
编辑:我正在检查分支v1.0.x的AngularJS代码,我找不到任何方法来更改查询字符串构造代码,这发生在这里:
https://github.com/angular/angular.js/blob/v1.0.x/src/ngResource/resource.js#L299-L306
有没有人有任何聪明的方法来覆盖ngResource类的那一部分?
解决方法
我的简单方案:
module.run(['$http','$httpParamSerializerJQLike',function($http,$httpParamSerializerJQLike) { $http.defaults.paramSerializer = $httpParamSerializerJQLike; }]);