【发布时间】:2015-11-24 12:52:24
【问题描述】:
我已经看到以下 SO 问题 Send array via GET request with AngularJS' $http service 和 Pass 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 似乎对我不起作用。我尝试了各种参数化身,生成的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, 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' }
})
但我想了解,如何使用参数来执行此操作,以便 AngularJS 为我执行此操作。
【问题讨论】:
-
你的角度版本是多少?我可以看到在 angular js 1.2.9 中有一个解决方法。虽然不确定
-
似乎
jQuery.param({numbers: [{ First: 999, Second: 888 }]})产生了您期望的结果。如果您的项目中已经有 jQuery,您可以使用它来为您构建 URL。 -
如果您有 jQuery,那么您可能可以通过 jQuery 创建参数并按如下方式使用它 -
var params = $.params({...});然后在角度url: url+'?'+params -
但是JQuery和AngularJS可以一起使用吗?