简体   繁体   English

使用javascript和php从mysql级联下拉菜单

[英]cascading dropdowns from mysql with javascript and php

EDIT: Solution at the bottom of this first entry. 编辑:解决方案在此第一个条目的底部。

I've been scouring SO for a good day or two now and am not having any luck coming up with getting my dynamic drop downs working. 我一直在搜索SO了好一两天,并且没有遇到让我的动态下拉列表起作用的任何运气。

I have a form. 我有一个表格。 The first dropdown is the customer field. 第一个下拉列表是“客户”字段。 What I want is when the customer is selected in the drop down, the terms associated with that customer are selected in the second dropdown. 我想要的是在下拉列表中选择客户时,在第二个下拉列表中选择与该客户关联的条款。 The Second dropdown always has the same options no matter what customer is chosen, its a matter of which of those options are "selected" for that particular customer. 无论选择哪个客户,“第二”下拉列表始终具有相同的选项,这与为该特定客户“选择”了哪些选项有关。

Here is what it looks like. 这是它的样子。

Dropdown1 (customer)
---------
Acme Corp
Contoso Inc
Smithville

Dropdown2 (terms)
---------
NET15
NET30
NET45

I want dropdown2 to change to the terms associated with that customer in the mysql database. 我希望dropdown2更改为与mysql数据库中与该客户相关联的条款。

I can't figure out if I should leave the dropdown options in the form itself and use javascript to call a php file to find out which is selected for that customer -or- if I should simply remove the entire options selection from the form and have javascript call that like I show in my work below. 我不知道是否应该将下拉选项保留在表单本身中,并使用javascript调用php文件来找出为该客户选择的选项-或者-如果我应该简单地从表单中删除整个选项,像我在下面的工作中显示的那样进行javascript调用。

Here is what I in the form for my two dropdowns, the second is from javascript with div. 这是我的两个下拉菜单的形式,第二个是来自div的javascript。

<td><select name="company" onchange="getTerms('terms');">
<option value="" selected></option>
<?php while($row = mysql_fetch_array($result)) {
  echo "<option value=\"".$row['company']."\">".$row['company']." (".$row['first']." ".$row['last'].")</option>"; } ?></select></td>

<td><div id="terms"></div></td>

And here is my php file that is supposed to be called from javascript. 这是应该从javascript调用的我的php文件。 What this does is get the options for the customer and selects the option that is selected. 这样做是为客户获取选项,然后选择所选的选项。 If I run this directly in the browser with ?id=acme corp it works fine so I know the php is working. 如果我直接使用?id = acme corp在浏览器中运行此程序,它将正常工作,因此我知道php在正常工作。

<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";


$result3 = mysql_query("SELECT * from netterms ORDER BY days ASC") or die(mysql_error());

$result = mysql_query("SELECT terms FROM customer WHERE company = '$_GET[id]'") or die(mysql_error());
$row = mysql_fetch_array($result);

echo "<option value=\"\" selected></option>";
while($row3 = mysql_fetch_array($result3)) {
  echo "<option value=\"".$row3['days']."\""; echo($row['terms'] == $row3['days']?' selected="selected"':null)?>><?php echo $row3['name']."</option>";

}
?>

And finally, here is my attempt at the javascript/jquery. 最后,这是我对javascript / jquery的尝试。

<script type="text/javascript">
 function getTerms(div){
    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
      var newdiv = document.createElement('div');
      newdiv.innerHTML = "<select name='terms'>" + xmlhttp.responseText + "</select>";
     }
      document.getElementById(div).appendChild(newdiv);
   }

 xmlhttp.open("GET", "customertermsdropdownquery.php?id=", false);
 xmlhttp.send();
 }
 </script>

What I am seeing is that everytime dropdown1 is changed, a new (additional) dropdown2 appears on the screen. 我看到的是,每次dropdown1更改时,屏幕上都会出现一个新的(附加)dropdown2。 I don't want multiple dropdowns appearing all over the page, just want the options in the dropdown to refresh. 我不希望整个页面上都出现多个下拉菜单,只希望刷新下拉菜单中的选项。 Also, I can't figure out how to pass ?id= to my php file from xmlhttp.open if you could help me out would be great! 另外,如果您能帮助我,我将不知道如何从xmlhttp.open传递?id =到我的php文件,这将是很棒的! thanks. 谢谢。

SOLVED: 解决了:

After several days of trying to get this to work, I stumbled upon a solution on another site. 经过几天的尝试,我偶然发现了另一个站点上的解决方案。 Here is the code. 这是代码。 What is important here is the careful use of div tags with table tags. 这里重要的是将div标签与表标签一起谨慎使用。 It goes like this which is not shown below in this authors code. 这样,下面的作者代码中未显示。

For me the td tags had to be here and not in the php. 对我来说,TD标签必须在这里,而不是在PHP中。 However, my select tags are in the php. 但是,我的选择标记在php中。 I really hope this is of value to someone searching. 我真的希望这对搜索的人有价值。

<html>
<head>
<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","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> 

You should probably use Ajax to load the php script every time the first select changes. 每次第一次选择更改时,您可能应该使用Ajax加载php脚本。

Adapted from sending http request with ajax each time select box is changed : 每次更改选择框时,改用ajax发送http请求

I tried adapting the answer to your question but I can't really test it: 我尝试调整答案以解决您的问题,但我无法真正对其进行测试:

$("#company").live('change',function() 
{
    var selectVal = $('#company :selected').val();


    var $terms = $('#terms').html('');

    $.ajax({                                      
      url: 'customertermsdropdownquery.php',                         
      data: "id="+selectVal,                                                     
      dataType: 'GET',                
      success: function(data)         
      {

              $terms.append(data);

      } 
    });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM