[英]How can I change a data element in a $.get using values from a JSON array?
如何使用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
運行3次並停止。 當然,如果數組中有更多值,則應使用所有這些值並停止。 值的計數應該是可變的。
在下面的示例中,如果我將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.
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.