簡體   English   中英

PHP和Ajax使用onchange事件

[英]PHP and Ajax using onchange event

我在cat.php文件中有以下代碼:

<script>
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getsub.php?q="+str,true);
xmlhttp.send();
}
</script>


<select name="users" onchange="showUser(this.value)">
<option value=""></option>
<?php
$query = "SELECT cat from category GROUP BY cat";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num=mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row=mysql_fetch_assoc($result);
echo "<option value=''>".$row['cat']."</option>";
}
echo "</select>";

<div id="txtHint"></div>

並在調用函數后getsub.php

<?php
require_once('connect_db.php');
//get the q parameter from URL
$q=$_GET["q"];

$query = "SELECT sub from category WHERE cat = '".$q."'";
$result = mysql_query($query);
if(!$result){
mysqli_error(); 
}

while ($row = mysql_fetch_assoc($result)){
?>
<select name="sub">
<?php
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
echo "<option value='".$row['sub']."'>".$row['sub']."</option>";
}
?>
<select>

<?php
}

我期待在主類別和子類別之間建立聯系。 我想選擇Main類別,然后調用javascript函數,以顯示Sub Category的另一個選擇輸入。 上面的代碼什么都不輸出,我似乎找不到原因?

請幫忙

代碼看起來不錯。 嘗試對Firefox使用firebug擴展。 在Firebug中打開網絡面板,然后查看您要發送的數據以及實際生成的響應。 這肯定會有所幫助。 同樣在cat.php中,請嘗試使用jQuery,而不是使用普通的AJAX,因為這會減少大行代碼,因為

// Just incude jQuery beforehand

script>
function showUser(str)
{
    $.get("getsub.php",{q:str},function(data){
        $("#txtHint).html(data);
   });
}
</script>

您的代碼看起來不錯,但是while循環的末尾只有一個php標記需要關閉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM