AngularJS使用Array参数调用ajax调用

前端之家收集整理的这篇文章主要介绍了AngularJS使用Array参数调用ajax调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经看到了以下SO问题 Send array via GET request with AngularJS’ $http servicePass array of data from Angular $http POST.但是建议的解决方案对我来说似乎没有用.我特别关注数组对象.

我有以下AngularJS ajax调用数组参数

return $http({
    method: 'GET',url: '/api/PatientCategoryApi/PatCat',params: { "numbers[]": [{ First: 999,Second: 888 }]},headers: { 'Content-Type': 'application/Json' }
})

调用生成的url似乎对我不起作用.我尝试了各种params的化身,并且生成的url(通过使用fiddler得到它们)如下.

params: { numbers: JSON.stringify([{ First: 999,Second: 888 }]) },http://localhost:50849/api/PatientCategoryApi/PatCat?numbers=%5B%7B%22First%22:999,%22Second%22:888%7D%5D 

params: { "numbers[]": JSON.stringify([{ First: 999,http://localhost:50849/api/PatientCategoryApi/PatCat?numbers%5B%5D=%5B%7B%22First%22:999,%22Second%22:888%7D%5D 

params: { "numbers[]": [{ First: 999,http://localhost:50849/api/PatientCategoryApi/PatCat?numbers%5B%5D=%7B%22First%22:999,%22Second%22:888%7D 

params: { numbers: [{ First: 999,%22Second%22:888%7D

我希望url是http://localhost:50849/api/PatientCategoryApi/PatCat?numbers[0][first]=999&numbers[0][second]=888.因为这是我的Asp.net MVC服务器端代码能够理解和解密数组的唯一方法.

一种方法是设置url本身以完全保持params,如下所示.以下是有效的.这是我的最后一个选择.

return $http({
    method: 'GET',url: '/api/PatientCategoryApi/PatCat?numbers[0][first]=999&numbers[0][second]=888&numbers[1][first]=9999&numbers[1][second]=8888',//params: {...},remove this completely
    headers: { 'Content-Type': 'application/Json' }
})

但我想了解,如何使用params这样做,所以AngularJS会为我做这件事.

解决方法

你想要 httpParamSerializerJQLike!像这样使用它:

$http({
  ...
  params: { "numbers": [{ First: 999,paramSerializer: '$httpParamSerializerJQLike',...
});

或者您可以将其设置为配置块中所有$http调用的默认值,如下所示:

angular.module('yourModuleName').config(function($httpProvider) {
  $httpProvider.defaults.paramSerializer = '$httpParamSerializerJQLike';
});

猜你在找的Angularjs相关文章