【问题标题】:Dynamically updating content of drop down menu when radio button value is changed using PHP, MySQL and AJAX使用 PHP、MySQL 和 AJAX 更改单选按钮值时动态更新下拉菜单的内容
【发布时间】:2014-11-26 23:29:39
【问题描述】:

我正在创建一个表单,其中有两个单选按钮和一个下拉列表。我希望当用户更改他们对单选按钮的选择时,下拉列表也会更改其值,这些值将从数据库表中选择,其中两列名称分别为 life 和 general。

这里是 request.php 的 sn-p

    <input type="radio" name="department" id="department" value="life" onchange="listDept(this.value)" checked>Life
    <input type="radio" name="department" id="department" value="general">General 
   </td>
</tr>
<tr>
  <td></td>
  <td></td>
  <td>
    <select name="department" id="listDept">
 </select>

这里是查询数据库的getdepartment.php文件:

<?php
require 'connectdb.php';

$department =NULL;
if(isset($_POST['department'])){$department = $_POST['department']; } 

if($department == "life")
{
	$query = "select life from tbl_departments";
	$result = mysqli_query($con, $query);

	while($row = mysqli_fetch_array($result))
		echo '<option>'.$row['life'].'</optiom>>';
}
if($department == "general")
{
	$query = "select general from tbl_departments";
	$result = mysqli_query($con, $query);

	while($row = mysqli_fetch_array($result))
		echo '<option>'.$row['general'].'</option>';
}

这是检查用户选择的 AJAX 脚本:

function listDept()
{
	var dept = document.getElementById("department").value;
	var xhr;
	if (window.XMLHTTPRequest) { //Mozilla, Safari...
		xhr = new XMLHTTPRequest();
	}
	else if (window.ActiveXObject) { //IE8 and older
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	}
	var data = "department" + dept;
	xhr.open("POST", "./parse_files_php/getdepartment.php", true);
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xhr.send(data);
	xhr.onreadystatechange = display_data;
	function display_data(){
		if(xhr.readyState==4){
			if (xhr.status==200) {
				document.getElementById("listDept").innerHTML = xhr.responseText;
			}
			else {
				alert('There was a problem with the request.');
			}

		}
	}
}

我没有从服务器获得任何反馈,即下拉列表未填充。

我的数据库连接工作正常。

【问题讨论】:

  • 你能告诉我们哪个部分不工作吗?您是没有从服务器取回数据,还是没有正确填充选择?任何 JS 错误?
  • @hukir 没有从服务器获取任何数据。下拉列表根本没有生成。
  • 你有重复的id="department",删除它并以这种方式获取价值:var dept = document.getElementsByName("department")[0].value;
  • 那么有几件事。您的选择与单选按钮具有相同的名称。 “通用”单选按钮需要一个 onchange 来调用 js 函数 listDept。如果你直接在浏览器中调用 getdepartment.php 文件,你会得到选项列表吗?
  • @skobaljic 我已经这样做了,但它似乎不起作用。

标签: javascript php mysql ajax html


【解决方案1】:

如果您愿意为页面脚本使用 jquery 来实现该功能 你可以参考我的示例。

HTML:

    <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="js/jquery-1.11.1.min.js"></script>
        <script>
            $(document).ready(function() {
                $("input[name='department']").click(function() {
                    //console.log($('input:radio[name=department]:checked').val());
                    getSelectOptions($('input:radio[name=department]:checked').val());
                    //AJAX CALL
                });
            });

            function getSelectOptions(radioVal) {
                $.ajax({
                    type: 'POST',
                    url: 'dbo.php',
                    data: {'radioval': radioVal},
                    success: function(data) {
                        //console.log(data);
                        updateSelect(data)
                    }
                });
            }

            function updateSelect(data) {
                var json = $.parseJSON(data);
                console.log(json);
                var selectHTML;
                $.each(json, function(key, value) {
                    console.log(value);
                    selectHTML += "<option value=" + value + ">" + value + "</option>";
                });
                $('#listDept').html(selectHTML);
            }
        </script>
    </head>
    <body>
        <form>
            <input type="radio" name="department" id="department" value="life">Life
            <input type="radio" name="department" id="department" value="general">General 
            <select name="department" id="listDept">
            </select>
        </form>
    </body>
</html>

还有我的虚拟 php 文件,它返回显然包含您的数据库调用等的列表条目。

dbo.php

<?php
$radio=$_REQUEST['radioval'];
$selectArray=array();
if($radio=='life'){
$selectArray[0]='life1';
$selectArray[1]='life2';
}else if($radio=='general'){
$selectArray[0]='general1';
$selectArray[1]='general2';

}
echo json_encode($selectArray);

试用示例并告诉我们这是否适合您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多