我有一个3步链式选择序列game -> battle -> winning side
,它从MySQL数据库中提取所有数据。
在互联网上徘徊之后,我发现了一个非常棒的jQuery脚本。但是,我不知道如何使用此脚本来允许现有数据:<option selected="selected"></option>
。
链接选择javascript:
<script>
var ajax = new Array();
function getScenNumList(sel)
{
var game = sel.options[sel.selectedIndex].value;
document.getElementById('scenarioNumber').options.length = 0; // Empty scenario number select box
if(game.length>0){
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'js/getPlayData.php?gameName='+game; // Specifying which file to get
ajax[index].onCompletion = function(){ createScenarioNumbers(index) }; // Specify function that will be executed after file has been found
ajax[index].runAJAX(); // Execute AJAX function
}
}
function createScenarioNumbers(index)
{
var obj = document.getElementById('scenarioNumber');
eval(ajax[index].response); // Executing the response from Ajax as Javascript code
}
function getNations(sel)
{
var scenNum = sel.options[sel.selectedIndex].value;
document.getElementById('victor').options.length = 0; // Empty nation select box
if(scenNum.length>0){
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'js/getPlayData.php?scenID='+scenNum; // Specifying which file to get
ajax[index].onCompletion = function(){ createNations(index) }; // Specify function that will be executed after file has been found
ajax[index].runAJAX(); // Execute AJAX function
}
}
function createNations(index)
{
var obj = document.getElementById('victor');
eval(ajax[index].response); // Executing the response from Ajax as Javascript code
}
</script>
摘自PHP数据库检索脚本(getPlayData.php
):
$gameName = mysql_real_escape_string($_GET['gameName']);
$q = "SELECT a, b, c FROM table WHERE game='$gameName' ORDER BY num ASC";
$r = mysql_query($q);
echo "obj.options[obj.options.length] = new Option('#','');\n";
while ($row = mysql_fetch_row($r)) {
$string = mysql_real_escape_string(($row[0].' - '.$row[1])); // needed so quotes ' " don't break the javascript
echo "obj.options[obj.options.length] = new Option('$string','$row[2]');\n";
}
回显obj.options
是此脚本使用的stock方法。这对我来说似乎很难看,但我不知道任何javascript,所以我不想乱用它。
HTML很简单,只是一个包含几个空<select>
个对象的表,其ID与javascript和onchange="getXXX(this)"
调用中的ID相匹配。
我的问题是:一切都适用于新记录,但我不知道如何改变它以支持从每个选择标记一个选项作为选择,假设我有手头的数据(例如:用户正在编辑现有记录)?
非常感谢!
答案 0 :(得分:1)
您可以看到本教程,用于创建默认选项。 http://www.javascriptkit.com/javatutors/selectcontent.shtml选项构造函数中的一个参数指示是否选择了该选项。
在PHP文件中,您将编辑如下:
$gameName = mysql_real_escape_string($_GET['gameName']);
$q = "SELECT a, b, c FROM table WHERE game='$gameName' ORDER BY num ASC";
$r = mysql_query($q);
echo "obj.options[obj.options.length] = new Option('#','');\n";
while ($row = mysql_fetch_row($r)) {
$string = mysql_real_escape_string(($row[0].' - '.$row[1])); // needed so quotes ' " don't break the javascript
if ($string ......)
echo "obj.options[obj.options.length] = new Option('$string','$row[2]', false, true);\n";
else
......
}