我有两个下拉列表,我希望根据从第一个下拉列表中选择的数据填充第二个下拉列表
这是我的main.php:
<?php
include('connection.php');
$query_religion="SELECT DISTINCT religion FROM religion_caste_table";
$result_religion = mysql_query($query_religion, $con);
?>
<html>
<body>
<select name="religion" id="religion" style="width: 100px" onChange="showcaste(this.value)">
<?php
while($q_rel_data = mysql_fetch_array($result_religion))
{?>
<option value="<?php echo $q_rel_data[0]; ?>">
<?php echo $q_rel_data[0]; ?>
</option>
<?php }?>
</select>
<div id="view"></div>
<select name="caste" id="caste" style="width: 100px"></select>
</body>
</html>这是getcaste.php:
<?php
include('connection.php');
$string=$_GET["religion"];
$sql="SELECT caste FROM religion_caste_table WHERE religion = '".$string."'";
$result = mysql_query($sql,$con);
$myarray=array();
$str="";
while($result_caste=mysql_fetch_array($result))
{
$str=$str . "\"$result_caste[caste]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo $str;/*Stop hiding from IE Mac */
//echo $string;
mysql_close($con);
?>
<html>
</html>现在是javascript ajax文件(religion_caste.js)
function showcaste(string)
{
if (string=="")
{
document.getElementById("caste").innerHTML="";
return;
}
alert(string);
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("view").innerHTML=xmlhttp.responseText;
//now how to catch the string from (getcaste.php), split it and save it into array
// and to populate the second dropdwn by the array;
}
}
xmlhttp.open("GET","getcaste.php?religion="+string,true);
xmlhttp.send();
}为了获得更好的帮助,数据库表包含两个字段,宗教和种姓,其中第一个属性是宗教,种姓是第二个属性。
如果我能以某种方式捕获字符串str,那么它就可以解决这个问题。
document.getElementById("view").InnerHTML=xmlhttp.responseText提供字符串"str1","str2",...要在<div id="view">中查看
但是如果我写下面的代码:
var string=(document.getElementById("view").InnerHTML);
alert(string);然后弹出一个msgbox,显示如下视图:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
"Catholic","Protestant" 如果我能拿到那根线,我会很高兴。
发布于 2012-02-25 14:02:41
因此,代替您的位置,a将在getcaste.php中进行一些重新制作,首先将查询的所有结果放入一个数组中,然后使用implode通过delimiter - ;获得一个字符串。(可选的是,您可以使用json并在js中对其进行解码)。在religion_caste.js中,使用split从其中获取一个数组(;作为分隔符);现在使用for cycle循环所有值,并在每个循环中向select添加一个选项
示例:
var select = document.getElementById("caste");
for (var key in values)
{
var OptNew = document.createElement('option');
OptNew.text = values[key];
OptNew.value = key;
try
{
select.add(OptNew, null); // doesn't work in IE
}
catch(ex)
{
select.add(OptNew); // IE only
}
}编辑:
所以php中的json很容易-- js中的json_encode json要难一点。新的浏览器应该支持JSON.parse,对于旧的浏览器,你必须使用这个code(这里不是100%确定,因为我总是使用jQuery)。或者,您可以使用jQuery和jQuery.parseJSON
https://stackoverflow.com/questions/9441504
复制相似问题