Asp.net mvc 如何根据数组的长度构建参数?
然后我希望能够将其发送到我的ajax get:Asp.net mvc 如何根据数组的长度构建参数?,asp.net-mvc,jquery,Asp.net Mvc,Jquery,然后我希望能够将其发送到我的ajax get: function BuildParams(arr) { // arr is an Array // how to build params based on the length of the array? // for example when arr.Length is 3 then it should build the below: var params = {
function BuildParams(arr)
{
// arr is an Array
// how to build params based on the length of the array?
// for example when arr.Length is 3 then it should build the below:
var params = {
'items[0]' : arr[0],
'items[1]' : arr[1],
'items[2]' : arr[2]
},
return params;
}
只需迭代数组,将数组中的每个元素添加为
params
对象的新属性:
var arr = ['Life', 'is', 'great'];
$.get('/ControllerName/ActionName', BuildParams(arr))
.done(function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
})
.fail(function(data) {
alert(data.responseText);
});
var params={};//从一个空对象开始
对于(变量i=0;i
:
通用迭代器函数,可用于无缝迭代
在对象和数组上。数组和具有
对length属性(例如函数的arguments对象)进行迭代
按数字索引,从0到长度-1。其他对象通过
它们的命名属性
将BuildParams(arr)
更改为:
var result = {}
jQuery.each(['Life', 'is', 'great'], function(index, value){
result['items[' + index + ']'] = value;
});
jQuery将正确地将对象序列化为查询字符串,包括带有数组项的对象。如果使用jQuery,为什么不使用?@zzbov可能是因为文档中有一行:“如果传递的对象是数组,则它必须是.serializeArray()返回格式的对象数组。”这表明它不能正确处理字符串数组。@AnthonyGrist,传入的对象应该是一个对象:
$.param({items:arr})
。目标是在items
$的键上设置值数组。param()在上述情况下没有帮助,因为它不生成{…}。{}
只是一个对象文本。
var result = {}
jQuery.each(['Life', 'is', 'great'], function(index, value){
result['items[' + index + ']'] = value;
});
{items: arr}