PHP-根据用户输入更新下拉列表中的值


PHP - Updating values in drop down list upon user input

我的php表单中有两个下拉列表。下拉列表中的值将从数据库(mysql)中检索。我已经运行了第一个下拉列表。但现在我需要根据用户的选择更新第二个下拉列表。第二个下拉列表中显示的值将根据用户的选择而推迟。

用户从第一个下拉列表中选择一个选项后,如何更新另一个下拉列表的值?我在SO上搜索并看到了类似的问题,但没有得到回答。希望能在这里得到一些帮助。谢谢下面是我当前的代码。

PS。如果我要创建一个html表单,我需要在启动时运行php脚本,而不需要任何输入来填充第一个下拉列表。我是怎么做到的?我只知道如何在输入时发送请求;例如<input type=submit>

.php

<?php
$conn = mysql_connect("127.0.0.1","root","")
mysql_select_db(MyApp,$conn);

$sql2=("SELECT App.AppName FROM App);               

$result2=mysql_query($sql2); 
echo '<select name="sublist">';
echo '<option value=""></option>';
while ($row2 = mysql_fetch_assoc($result2))
{
    echo '<option value="' . $row2['AppName'] . '">' . $row2['AppName']. '</option>';
}
echo '</select>';                                           
?>

您有两种解决方案。

  1. 完全使用PHP(我不推荐,因为它对用户不太友好)
  2. 基于Ajax(更加用户友好)

然而,要以良好的方式执行这两件事,您需要Javascript 的支持

所以,如果我向你解释解决方案一。一旦用户更改了您的第一个下拉列表。您必须使用onChange()事件将页面POST到同一页面。然后在您的页面中,将第二个下拉列表的元素设置为与第一个下拉列表相同的元素。

第二个解决方案需要AJAX。一旦用户更改了第一个下拉列表,您就会向页面发出AJAX请求。在该页面中,您可以看到用户所做的选择。然后基于此生成第二个下拉列表。在这里,您可以使用三种方法来获取第二个下拉列表或它的数据。

a。您从该页面生成所有选项并发回。设置第二个下拉列表的innerHTML。

b。以JSON形式获取数据,并在此基础上填充下拉列表。

c。获取AJAX XML并在此基础上填充下拉列表。

有不止一种方法可以做到这一点:

1) 将一个带有用户选择的请求发送到服务器,检索第二个选择框的内容并显示它a) AJAX——因此页面不会刷新(平滑的用户体验)b) 刷新整个页面--(实现起来更简单)

2) 加载所有组合,然后根据用户的选择,显示特定的下拉列表。只有当您有很少组合的小下拉列表时,这才是可行的(就不生成大页面而言)。

正如另一位发帖者所指出的,所有方法都需要JavaScript(在某种程度上)才能运行。请详细说明哪种方法是可取的,我将进一步详细介绍

查看源代码以复制代码。JQuery有一种简单的方法。我使用了一个我自定义的表单创建者。但这里是输出-手动方式。

这是您的ajax文件。它位于JS或标头中。

    function getXMLObject()  //XML OBJECT
    {
       var xmlHttp = false;
       try {
         xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
       }
       catch (e) {
         try {
           xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
         }
         catch (e2) {
           xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
         }
       }
       if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
         xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
       }
       return xmlHttp;  // Mandatory Statement returning the ajax object created
    }
    var xmlhttp = new getXMLObject();   //xmlhttp holds the ajax object
    function makeAjaxRequest(url, params, output, image) {
      var getdate = new Date();  //Used to prevent caching during ajax call
      if( image == 1 ){
          document.getElementById(output).innerHTML='<img src="./images/template/ajax-loader.gif"></img>'; 
      }
      if(xmlhttp) { 
        xmlhttp.open("POST",url,true); //calling testing.php using POST method
        xmlhttp.onreadystatechange = function(){
           if (xmlhttp.readyState == 4) {
             if(xmlhttp.status == 200) {
               document.getElementById(output).innerHTML=xmlhttp.responseText; //Update the HTML Form element 
             }
             else {
    //          alert("Error during AJAX call. Please try again");
             }
           }    
        }
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send(params); //Posting txtname to PHP File
      }
    }
    function makeAjaxGetRequest(url, output, image) {
      var getdate = new Date();  //Used to prevent caching during ajax call
      if( image == 1 ){
          document.getElementById(output).innerHTML='<img src="./images/template/ajax-loader.gif"></img>'; 
      }
      if(xmlhttp) { 
        xmlhttp.open("GET",url,true); //calling testing.php using GET method
        xmlhttp.onreadystatechange = function(){
           if (xmlhttp.readyState == 4) {
             if(xmlhttp.status == 200) {
               document.getElementById(output).innerHTML=xmlhttp.responseText; //Update the HTML Form element 
             }
             else {
    //          alert("Error during AJAX call. Please try again.");
             }
           }    
        }
        xmlhttp.send(null); //Posting txtname to PHP File
      }
    }
    function emptyAjaxReportBox(id)
    {
        document.getElementById(id).innerHTML= '';
    }

以下是用户导航到的文件:

// your call file; what you posted above.  Obviously change the names and Id's to match what you need.
<form  id="testFormId"  name="testForm"  action="post" >
<select  id="firstSelectId"  name="firstSelect"  onchange="makeAjaxRequest('url', 'firstSelect='+encodeURIComponent(document.getElementById('firstSelectId').value),'outputDivId', '0');" >
</select>
<div  id="outputDivId" >
<select name="secondInput">Whatever values you want to load up can go in here.  They can be the default values; meaning, if select 1 value = 0, then you have have these values in select 2.  Once you change select 1, this will disappear and be replaced by what your ajax returns.  Therefore, for easy processing after you submit the form, you should make this select 2 the same name and id as what you use in the ajax.</div>
</form>

这是在ajax请求时调用的文件。

//your AJAX file needs to be a separate page than what you're currently reading.  Put whatever you want in there.
$db = connectioninfo;
$query;
echo 'What you put in the echo is what will show up in the outputDiv.  <select></select>';