【问题标题】:chained selection using drop down使用下拉列表进行链式选择
【发布时间】:2015-05-02 09:25:49
【问题描述】:

在下面的这段代码中,我将数据库中的主题列表打印到下拉列表中。选择主题后,下一个名为 section 的下拉菜单应通过在数据库中查找主题名称来显示每个主题的部分。

这是我能够做的,但它不起作用,任何帮助的人,请忽略我的编码风格,因为我是初学者。提前谢谢你。

主要代码:

    <div>
      Subject:
  <?php
        $conn = new mysqli('fgdfgfg', 'fggfdgfr', 'fgfgf', 'fgfgfgf') or die('Cannot connect to db');
        $result = $conn->query("select name from class");
        echo "<select name='subject' nChange='getSection('findsection.php?subject='+this.value)'>";
        while ($row = $result->fetch_assoc()) {
            unset($id, $name);
            $name = $row['name'];
            echo '<option value="subject">' . $name . '</option>';
        }
        echo "</select>";
        ?> 
    </div>
    <br>  
    <div id="sectiondiv">
        Section: 
        <select name="select">
        </select>
    </div>

findsection.php

<? $subject=intval($_GET[‘subject’]);;
$servername = "localhost";
$username = "fhdfhdfhf";
$password = "ghhfghgh";
$dbname = "ghghgh";
$mysqli  = new Mysqli($servername, $username, $password, $dbname) or mysqli_error($mysqli);
$section = $mysqli->query("SELECT section FROM class WHERE name = '$subject'")->fetch_object()->section; 
$result=mysql_query($section);?>
<select name="section">
<? while ($row = $result->fetch_assoc()) { ?>
   <option value><?=$row['section']?></option>
<? } ?>
</select>

JS代码:

<script type="text/javascript">
function getSection(strURL)
{         
 var req = getXMLHTTP(); // fuction to get xmlhttp object
 if (req)
 {
  req.onreadystatechange = function()
 {
  if (req.readyState == 4) { //data is retrieved from server
   if (req.status == 200) { // which reprents ok status                    
     document.getElementById('sectiondiv').innerHTML=req.responseText;
  }
  else
  { 
     alert("There was a problem while using XMLHTTP:\n");
  }
  }            
  }        
req.open("GET", strURL, true); //open url using get method
req.send(null);
 }
}
</script>

【问题讨论】:

  • 让它正确 nChange='getSection 它将是 onchange='getSection
  • 您可以更明确地说明您的代码何时停止工作。是的,也许 javascript 函数没有被调用,或者 XHR 甚至数据库出错。你必须想出调试的方法。 (警报控制台日志响应..萤火虫工具等,..)
  • @saty 已修复,但代码仍无法正常工作。

标签: javascript php html mysqli


【解决方案1】:

问题似乎出在这条线上

<select name='subject' onchange='getSection('findsection.php?subject='+this.value)'>

this.value 没有按照您的意愿传递。这里this 的值是window 对象而不是select 标签对象。

所以我建议你在getSection函数本身中获取当前值的值,并在函数内部形成url,然后进行http请求。

【讨论】:

  • aww 谢谢你的帮助,但我不是那么好,哈哈。嗯,有什么小的指导提示吗?
  • 我认为调试代码的最佳方法是首先定位可能出现错误的区域。在javascript中,您可以使用console.log函数在程序的每一步打印出Web控制台上的日志。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多