如何使用 JSON 数组中的值更改 $.get 中的数据元素?
以下是执行一次操作的代码示例:
$.get(url, {
'p': testerName,
'magic': 'magic', //this value is constant now but may change
'init': init1 //this is the value I want to change from a value in a JSON array
}, function() {
// console.log('done');
});
我要更改的值是“init”。例如,如果“init1”位于类似于以下内容的 JSON 数组中:
"initvalues":[
{"init1":"usethisfirst"},
{"init1":"usethissecond"},
{"init1":"usethisthird"}
]
我希望 $.get
运行三次并停止。当然,如果数组中有更多值,则应该使用所有值并停止。值的计数预计是可变的。
在下面的示例中,如果我命名为 var init1 = usethisfirst
它将运行一次。
$.get(url, {
'p': testerName,
'magic': 'magic', //this value is constant now but may change
'init': init1 //this is the value I want to change from a value in a JSON array
}, function() {
// console.log('done');
});
而且,我可以对“init1”的每个不同值重复该例程,但我知道一定有更好的方法。
其他信息:
目标是避免硬编码重复的 $.get
函数,并使用一个根据 JSON 数组中值的数量运行 n 次的函数。
最佳答案
最简单的方法可能是使用 forEach
之类的东西执行 get 请求。如果您只想从某些 init1
值中设置 init
字段,您可以尝试如下操作:
var init_values = [
{"init1" : "use this first"},
{"init1" : "use this second"},
{"init1" : "use this third"}
];
init_values.forEach(function(settings) {
$.get(url, {
'p' : testerName,
'magic' : 'magic',
'init': settings['init1']
}, function() {
// Do something for this particular request.
});
});
但是,根据 JSON 数组的来源,您可能还对自动设置其他字段感兴趣:
var init_values = [
{
"p" : "some value",
"magic" : "magic",
"init" : "use this first"
},
{
"p" : "a different value",
// No value for magic - use default.
"init" : "use this second"
},
{"init" : "use this third"} // Use defaults for 'p' and 'magic'.
];
init_values.forEach(function(settings) {
var defaults = {
"p" : "default p",
"magic" : "default magic",
"init" : "default init"
};
$.get(url, $.extend(defaults, settings), function() {
// Do something for this request.
});
});
关于javascript - 如何使用 JSON 数组中的值更改 $.get 中的数据元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35856619/