我有三个选择,看起来像这样:
<select name="nick">
<?php foreach ($chars as $char):?>
<option value='<?php echo $char['name'] ?>'><?php echo $char['name'] ?></option>
<?php endforeach; ?>
</select>
<select name='faction' disabled>
<option value='ally'>Alliance</option>
<option value='horde'>Horde</option>
</select>
<select name='class' id="class" disabled>
<option value='1'>Warrior</option>
<option value='2'>Paladin</option>
<option value='3'>Hunter</option>
<option value='4'>Rogue</option>
<option value='5'>Priest</option>
<option value='6'>Death Knight</option>
<option value='7'>Shaman</option>
<option value='8'>Mage</option>
<option value='9'>Warlock</option>
<option value='10'>Druid</option>
</select>
$ chars:
$chars = array(0 => array("name" => "Solock",
"level" => "80",
"class" => "9"),
1 => array("name" => "Emmorts",
"level" => "80",
"class" => "3"),
2 => array("name" => "Ghom",
"level" => "80",
"class" => "2"),
);
$json = json_encode($chars);
JSON数组:
[
{"name":"Solock","level":"80","class":"9"},
{"name":"Emmorts","level":"80","class":"3"},
{"name":"Ghom","level":"80","class":"2"}
]
JSON对象:
{
"0":{"name":"Solock","level":"80","class":"9"},
"1":{"name":"Emmorts","level":"80","class":"3"},
"2":{"name":"Ghom","level":"80","class":"2"}
}
是否有可能,每当我更改[name = nick]选项时,其他选择将使用来自JSON对象或数组的数据进行选择(如果我选择“Ghom”,它会选择联盟和死亡骑士)?怎么样?
谢谢。
答案 0 :(得分:1)
首先 - 在服务器上并基于数据库条目 - 创建一个JSON字符串:
{
"Solock": ["ally", "9"],
"Emmorts": ["ally", "3"],
"Ghom": ["ally", "6"]
}
接下来,在客户端上,将该JSON字符串加载到JavaScript对象中。现在,您可以使用jQuery和该对象:
var $selectNick = $('select[name=nick]'),
$selectFaction = $('select[name=faction]'),
$selectClass = $('select[name=class]');
$selectNick.change(function() {
var value = this.value;
$selectFaction.val( json[value][0] );
$selectClass.val( json[value][1] );
});
(这里,json
变量是从JSON字符串创建的对象。)
答案 1 :(得分:1)
这是可能的。我建议您查看json_encode()
PHP函数。您应该能够使用该函数将$chars
变量编码为JSON。然后,您可以使用jQuery的parseJSON
方法基于JSON字符串创建JavaScript对象。
如果您不需要使用$char['name']
作为select
的值,那么您可能需要考虑使用索引(从0开始)轻松引用JavaScript对象。