JQuery:从数据库加载数据并将其插入到选择中

时间:2011-01-02 17:34:48

标签: php jquery mysql

我有三个选择,看起来像这样:

<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”,它会选择联盟和死亡骑士)?怎么样?

谢谢。

2 个答案:

答案 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字符串创建的对象。)

工作演示: http://jsfiddle.net/tgeVh/

答案 1 :(得分:1)

这是可能的。我建议您查看json_encode() PHP函数。您应该能够使用该函数将$chars变量编码为JSON。然后,您可以使用jQuery的parseJSON方法基于JSON字符串创建JavaScript对象。

如果您不需要使用$char['name']作为select的值,那么您可能需要考虑使用索引(从0开始)轻松引用JavaScript对象。