我想创建一个基于 mysql 数据库和表的动态下拉列表。我在网上搜索了一下,最接近 http://www.plus2net.com/php_tutorial/ajax_drop_down_list.php
我已经按照示例暗示了这段代码,第一个下拉框工作正常,但是一旦选择了"类别",第二个下拉框就不会填充。
代码为:
主.php
<html>
<body>
<script type="text/javascript">
function AjaxFunction(cat_id) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for (j = document.testform.subcat.options.length - 1; j >= 0; j--) {
document.testform.subcat.remove(j);
}
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url = url+"?cat_id="+cat_id;
url = url+"&sid="+Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<form name="testform" method='POST' action='mainck.php'>Name:<input type=text name=fname>
Select first one <select name=cat onchange="AjaxFunction(this.value);">
<option value=''>Select One</option>
<?
require "config.php";// connection to database
$q=mysql_query("select * from categories");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<select name=subcat>
</select><input type=submit value=submit>
</form>
</body>
</html>
而 dd.php 是
<?
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysql_query("select subcategory from subcategory where cat_id='$cat_id'");
echo mysql_error();
$myarray=array();
$str="";
while($nt=mysql_fetch_array($q)){
$str=$str . ""$nt[subcategory]"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";
?>
如前所述,main.php 正确加载和填充第一个下拉框。选择值后,第二个框中不会显示任何内容。为了测试,我将 dd 中的 mysql 查询从 dd.php
$q=mysql_query("select subcategory from subcategory where cat_id='$cat_id'");
自
$q=mysql_query("select subcategory from subcategory where cat_id=1");
然后在选择"类别"时填充第二个框。我认为所选值没有从 main.php 正确地传递到 dd.php
$cat_id=$_GET['cat_id'];
任何这方面的帮助将不胜感激。我有一种感觉,这是一件小事,但不能完全把我的手指放在上面。
一如既往地提前感谢。更新的问题
主.php
<form name='testform' method='POST' action='mainck.php'>
Name: <input type='text' name='fname'>
Select first one
<select name='cat' onchange='AjaxFunction(this);'>
<option value=''>Select One</option>
<?php
require "config.php";// connection to database
// I will continue to use mysql_query(), but please migrate you code to
// PDO or MySQLi ASAP
$query = "
SELECT cat_id,category
FROM categories
";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo "<option value='{$row['cat_id']}'>{$row['category']}</option>";
}
?>
</select>
<select name='subcat' id='subcat_select'>
</select>
<input type='submit' value='Submit'>
</form>
日.php
<?php
require "config.php";
$query = "
SELECT packcode
FROM skudata
WHERE cat_id='".mysql_real_escape_string($_GET['cat_id'])."' ";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[] = $row['packcode'];
}
echo json_encode($array);
?>
随着戴夫添加的更改,我无法让新的 mysql 表和引用列正常工作。已经测试了mysql,它运行良好。任何帮助,不胜感激。
谢谢
首先,阻止代码工作的小事情是传递给函数的值。对于<select>
元素this.value
将不起作用。相反,您需要使用 this.options[this.selectedIndex].value
.这样:
<select name=cat onchange="AjaxFunction(this.options[this.selectedIndex].value);">
现在,有关代码的一些注释:
- 切勿使用
eval()
。曾。任何语言。正确的用例是如此之少,而且相距甚远,以至于只说"永远不要使用它"要简单得多。 - 不要使用
mysql
扩展。请改用PDO
或MySQLi
。 - 你的代码中有一个巨大的SQL注入漏洞。
- 请合理地缩进您的代码。它使调试变得更加容易。你发布的那个杂乱无章的肿块几乎无法阅读。
- 不要使用
document.elementName
访问页面上的元素。给你的元素 ID 并改用document.getElementById('elementId')
- 它可以在任何地方工作,而命名元素则不然。 - 不要使用 PHP 短开放标签
<?
,使用完整的<?php
标签 - 同样,它在任何地方都有效,而短标签则不然。
以下是我编写代码的方法:
主.php
<html>
<head>
<!-- Omitting the <head> is very bad practice... -->
<title>My Page</title>
<script type='text/javascript'>
function GetAjaxObject () {
// Wrap the code for fetching an AJAX object in a separate function
// so it can be easily re-used
if (window.XMLHttpRequest !== undefined) {
return new XMLHttpRequest();
}
var xhr = null;
var axo = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
for (var o in axo) {
try {
xhr = new ActiveXObject(axo[o]);
} catch (e) {}
}
if (xhr !== null) {
return xhr;
} else {
throw new Error('Your browser does not support AJAX');
}
}
function ChangeSelect (element) {
// We are now passing the select element itself in, not just a value
var xhr, url;
// Fetch an AJAX object
try {
var xhr = GetAjaxObject();
} catch (e) {
alert(e.message);
return;
}
// Build the URL
url = "dd.php"
+ "?cat_id="+element.options[element.selectedIndex].value
+ "&sid="+Math.random();
// If it still doesn't work, uncomment this line to inspect the url
// alert(url);
// Define the readystatechange callback
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) { // Don't forget to check the status code
// I shall leave this eval() here for now, but really you should
// use a safe JSON library like http://www.json.org/js.html
var myarray = eval(httpxml.responseText);
// Start by getting a safe reference to the destination select
var dest = document.getElementById('subcat_select');
// Before adding new we must remove previously loaded elements
for (j = dest.options.length - 1; j >= 0; j--) {
dest.remove(j);
}
// Loop data from the server and create new options
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("option");
optn.text = myarray[i];
optn.value = myarray[i];
dest.options.add(optn);
}
} else {
alert("Server returned error " + xhr.status);
}
}
};
// Start the request
httpxml.open("GET", url, true);
httpxml.send(null);
}
</script>
</head>
<body>
<form name='testform' method='POST' action='mainck.php'>
Name: <input type='text' name='fname'>
Select first one
<select name='cat' onchange='AjaxFunction(this);'>
<option value=''>Select One</option>
<?php
require "config.php";// connection to database
// I will continue to use mysql_query(), but please migrate you code to
// PDO or MySQLi ASAP
$query = "
SELECT *
FROM categories
";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo "<option value='{$row['cat_id']}'>{$row['category']}</option>";
}
?>
</select>
<select name='subcat' id='subcat_select'>
</select>
<input type='submit' value='Submit'>
</form>
</body>
</html>
日.php
<?php
require "config.php";
$query = "
SELECT subcategory
FROM subcategory
WHERE cat_id='".mysql_real_escape_string($_GET['cat_id'])."'
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[] = $row['subcategory'];
}
echo json_encode($array);
?>
这段代码不起作用,因为这一切都是main.php文件
<script type="text/javascript">
function AjaxFunction(cat_id)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
var myarray=eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for(j=document.testform.subcat.options.length-1;j>=0;j--)
{
document.testform.subcat.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<form name="testform" method='POST' action='mainck.php'>
Select first one <select name=cat onchange="AjaxFunction(this.value);">
<option value=''>Select One</option>
<?
require "config.php";// connection to database
$q=mysql_query("select * from it_category ");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<select name=subcat>
</select><input type=submit value=submit>
</form>
</body>
</html>
这是DD.php
<?
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysql_query("select * from it_subcategory where cat_id='$cat_id'");
echo mysql_error();
$myarray=array();
$str="";
while($nt=mysql_fetch_array($q)){
$str=$str . ""$nt[subcategory]"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";
?>