小编典典

带有Array参数的AngularJS GET ajax调用

angularjs

我已经看过以下SO问题,即使用AngularJS的$http服务通过GET请求发送数组,以及通过Angular $ http
POST传递数据数组。但是那里建议的解决方案似乎对我不起作用。我的专门针对 数组对象

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

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

该调用生成的网址似乎不适用于我。我已经尝试了各种参数的化身,并且生成的网址(通过提琴手将其获取)如下。

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, Second: 888 }]) },
http://localhost:50849/api/PatientCategoryApi/PatCat?numbers%5B%5D=%5B%7B%22First%22:999,%22Second%22:888%7D%5D

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

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

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

一种方法是将url本身设置为完全容纳参数,如下所示。以下工作。这是我的最后选择。

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会为我做到这一点。


阅读 266

收藏
2020-07-04

共1个答案

小编典典

您需要httpParamSerializerJQLike!像这样使用它:

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

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

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