简体   繁体   English

使用循环动态更改Ajax数据

[英]Changing Ajax data dynamically using a loop

The code below passes four parameters (names) to a PHP file and it works fine. 下面的代码将四个参数(名称)传递给PHP文件,并且工作正常。 Because in my application I have more than 4 names that change with time, I tried to use a loop with array and specify "n" as the number of names that I may have. 因为在我的应用程序中,我有4个以上的名称随时间变化,所以我尝试使用带有数组的循环,并指定“ n”作为我可能拥有的名称数量。 I could not find a way that made it work correctly. 我找不到使它正常工作的方法。 Can you show me how to change the working code below to include a loop where the number of names "n" is a variable. 您能告诉我如何更改下面的工作代码,以包括名称为“ n”个变量的循环。

var name1 = "a";
var name2 = "b";
var name3 = "c";
var name4 = "d";

$.ajax({
    type: 'GET',
    url: 'test12.php',
    data: { par1: name1, par2: name2, par3: name3, par4: name4 },

});

Thnak you very much. 非常感谢您。

If all the names are globals, I would do: 如果所有名称都是全局名称,我会这样做:

var data = {}, n = 4;
for (i = 1; i <= n; i++)
    data['par'+i] = window['name'+i];

$.ajax({
    type: 'GET',
    url: 'test12.php',
    data: data // can be short-handed as "data" instead of "data: data"
});

If they are not globals, I would put the names in an array, and then loop through them this way instead: 如果它们不是全局变量,则将名称放入数组中,然后以这种方式遍历它们:

var data = {}, names = [name1, name2, name3, name4], n = names.length;
for (i = 1; i <= n; i++)
    data['par'+i] = names[i-1];

$.ajax({
    type: 'GET',
    url: 'test12.php',
    data
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM