如何在不使用PHP中的AJAX提交表单和页面刷新的情况下从数据库动态填充下拉框?

时间:2022-11-24 15:42:04

I have a PHP file in which there is a form and which has two Select drop down box. The first select box is filled with some value.

我有一个PHP文件,其中有一个表单,并有两个选择下拉框。第一个选择框中填充了一些值。

The Secont select box is empty.

Secont选择框为空。

As per requirement if some value is selected from first drop down box the second box should be get filled with some values from database.

根据要求,如果从第一个下拉框中选择了某个值,则第二个框应该从数据库中填充一些值。

I want to achive this using AJAX.

我想用AJAX来实现这个目标。

I got a code from http://www.w3school.com site. But in following that there is only one dropdown box and on onchange event the related values of selected value are showed in table format.I can replace that html code for table in the code with my second select box. But as per requirement I want to show second select dropdown box empty before selection which should get filled as per the selection in first select box dynamically and from database. So friends please tell me how to solve this problem. If you dont understand the following code because of formatting; then the same code that I got from http://www.w3school.com site is on the following link on same site.

我从http://www.w3school.com网站获得了一个代码。但是在下面只有一个下拉框和onchange事件中,所选值的相关值以表格格式显示。我可以用我的第二个选择框替换代码中的表的html代码。但是根据要求,我想在选择之前显示第二个选择下拉框为空,应根据第一个选择框中的选择动态地从数据库中填充。所以朋友请告诉我如何解决这个问题。如果您因格式化而不理解以下代码;然后我从http://www.w3school.com网站获得的相同代码在同一网站上的以下链接中。

http://www.w3schools.com/php/php_ajax_database.asp

http://www.w3schools.com/php/php_ajax_database.asp

This is the HTML page with ajax code

这是带有ajax代码的HTML页面

<html>
<head>
<script type="text/javascript">
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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>

This is the PHP file which is located on server and get called using AJAX and fetches the values from database

这是位于服务器上的PHP文件,使用AJAX调用并从数据库中获取值

<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
 }
 mysql_select_db("ajax_demo", $con);
 $sql="SELECT * FROM user WHERE id = '".$q."'";
 $result = mysql_query($sql);
 echo "<table border='1'>
 <tr>
 <th>Firstname</th>
 <th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

Please Guide me friends. Thank You!

请指导我的朋友。谢谢!

1 个解决方案

#1


1  

instead of echoing the results back in table row form, perhaps send them back in JSON format like this. you should also do some sort of check against SQL injection through casting (if your 'q' variable is a number) or mysql_real_escape_string().

而不是以表格形式回显结果,也许以这样的JSON格式发回它们。您还应该通过强制转换(如果您的'q'变量是数字)或mysql_real_escape_string()来对SQL注入进行某种检查。

PHP file:

PHP文件:

<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT `yourFieldName`, `yourFieldValue` FROM `yourTable` WHERE id = '".$q."'";
$result = mysql_query($sql);
$i = 0;
while ( $row = mysql_fetch_assoc($result) )
{
    $return[$i] = $row;
    $i++
}
$return["size"] = $i;
mysql_close($con);
echo json_encode($return);
?>

now all that needs changed in the javascript file is this:

现在javascript文件中所有需要改变的是:

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var responses = JSON.parse(xmlhttp.responseText);
        var size = responses.size;
        var selectBox =document.getElementById("yourSecondSelectBox");

        //clear any previous entries
        selectBox.options.length=0;
        for (var i = 0; i < size; i++){
            selectBox.options[i]=new Option(responses.i.yourFieldName, responses.i.yourFieldValue, false, false)
        }
    }
}

of course, you need to download and include the JSON js file in your html 'head' tag. alternatively, you could include jquery and use their built in AJAX and JSON support, but that will require more research on your part.

当然,您需要在html'head'标签中下载并包含JSON js文件。或者,您可以包含jquery并使用其内置的AJAX和JSON支持,但这需要您进行更多的研究。

#1


1  

instead of echoing the results back in table row form, perhaps send them back in JSON format like this. you should also do some sort of check against SQL injection through casting (if your 'q' variable is a number) or mysql_real_escape_string().

而不是以表格形式回显结果,也许以这样的JSON格式发回它们。您还应该通过强制转换(如果您的'q'变量是数字)或mysql_real_escape_string()来对SQL注入进行某种检查。

PHP file:

PHP文件:

<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT `yourFieldName`, `yourFieldValue` FROM `yourTable` WHERE id = '".$q."'";
$result = mysql_query($sql);
$i = 0;
while ( $row = mysql_fetch_assoc($result) )
{
    $return[$i] = $row;
    $i++
}
$return["size"] = $i;
mysql_close($con);
echo json_encode($return);
?>

now all that needs changed in the javascript file is this:

现在javascript文件中所有需要改变的是:

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var responses = JSON.parse(xmlhttp.responseText);
        var size = responses.size;
        var selectBox =document.getElementById("yourSecondSelectBox");

        //clear any previous entries
        selectBox.options.length=0;
        for (var i = 0; i < size; i++){
            selectBox.options[i]=new Option(responses.i.yourFieldName, responses.i.yourFieldValue, false, false)
        }
    }
}

of course, you need to download and include the JSON js file in your html 'head' tag. alternatively, you could include jquery and use their built in AJAX and JSON support, but that will require more research on your part.

当然,您需要在html'head'标签中下载并包含JSON js文件。或者,您可以包含jquery并使用其内置的AJAX和JSON支持,但这需要您进行更多的研究。