具有PHP功能的自适应下拉菜单从MySQL服务器填充

时间:2015-12-29 21:09:38

标签: javascript php jquery html mysql

我有三个下拉菜单,我一直试图依赖彼此,这样一旦在第一个下拉菜单中做出选择,第二个菜单的选项将会改变。然后,在第二个下拉菜单中进行选择后,第三个下拉菜单将会更改。我的HTML看起来像这样:

<select class = "homepageSelectors , hpSelectorMenu" id = "classSelector" name="classSelector" >
    <option selected="selected">Select</option>
    <option value= "geometry">Geometry</option>
    <option value= "english1">English 1</option>
    <option value= "algebra2">Algebra 2</option>
</select>

<select class = "homepageSelectors , hpSelectorMenu" id = "levelSelector" name="levelSelector">

</select>

<select class = "homepageSelectors , hpSelectorMenu" id = "teacherSelector" name="teacherSelector">

</select>

第一个下拉列表是硬编码的,因为选项不会改变。虽然,我需要做的是当第一个更改时,运行PHP函数来查询SQL数据库并获取第二个下拉菜单的选项。我在另一个文件中有以下jquery代码,该文件在第一个下拉列表更改时运行一个函数。

$("#classSelector").change( function () {
    //In here is where I need to run a PHP function
});

我意识到我可以从那个jquery函数调用一个外部PHP文件,虽然我的问题是,一旦我从该外部PHP文件查询我的SQL服务器,我就无法将查询结果返回给我的HTML文件,以便可以填充第二个下拉菜单。

我一直在寻找其他试图寻找解决方案的论坛,虽然我无法找到与我的场景相似的任何帖子。我对ajax不是很熟悉,但如果你认为这是方法,请解释。感谢所有的帮助!!!

2 个答案:

答案 0 :(得分:0)

您需要使用jQuery Ajax

请求.php文件以获取所需的数据。一个简单的例子让你有个想法:

您的javascript函数文件:

$("#classSelector").change( function () {
    //In here is where I need to run a PHP function

    var value = $(this).val();
    // load data if value is different than 'selected'
    if(value != 'selected') {
        $.ajax({
            url: 'your_file.php',
            data: {classID: $(this).val()},
            dataType: 'html',
            type: "GET",
            success: function(data) {
                // drop the output in #levelSelector select
                $('select#levelSelector').html(data);
            }
        });
    }
});

这可以转换为类似your_file.php的内容?classID = Geometry例如:

你的php文件:

<?php

// This is an example your php script should output what you need 
// and how you need even if loading data from SQL Server / MySQL etc...

$classID = (isset($_GET['classID'])) ? $_GET['classID'] : null;

switch($classID)
{
    case 'Geometry':
    echo "<option value='level1'>Level 1</option>";
        break;
    default:
    break;
}

// Output
<option value='level1'>Level 1</option>

输出将在&#39;#levelSelector&#39;内。选择并喜欢这个:

<select class = "homepageSelectors , hpSelectorMenu" id = "levelSelector" name="levelSelector">
    <option value='level1'>Level 1</option>
</select>

答案 1 :(得分:0)

所以,我认为你在这里真正要求的是:我如何使用JavaScript和PHP来实时查询数据库?

这有两个部分。 JavaScript脚本和PHP脚本。 JavaScript将对PHP脚本进行AJAX调用,然后PHP脚本将查询数据库并将该查询的结果返回给发出初始请求的JavaScript。

看起来你已经在使用jQuery了,所以这很棒,因为jQuery有一个非常有用的功能来进行网络调用:$.ajax()

获取您已有的代码并进行扩展:

$("#classSelector").change( function () {
  var selectedClass = $(this).find(":selected").text();

  $.ajax({
    url: '/path/to/class/select/php/script.php',
    data: {selectedValue: selectedClass}, // Send this data to the PHP script
    dataType: 'json', // Let's assume the PHP script will send us a JSON response
    success: function(data) { // Gets called if the entire request is successful
      console.log('Server returned level options for class ' + selectedClass, data);
      // data now contains the array of options for levelSelector.
      // I'm going to assume you know how to loop through them and populate levelSelector
    }
  });
});

我们需要levelSelector完全相同的代码,只需更改两件小事:

$("#levelSelector").change( function () {
  var selectedLevel = $(this).find(":selected").text();

  $.ajax({
    url: '/path/to/level/select/php/script.php',
    data: {selectedValue: selectedLevel}, // Send this data to the PHP script
    dataType: 'json', // Let's assume the PHP script will send us a JSON response
    success: function(data) { // Gets called if the entire request is successful
      console.log('Server returned teacher options for class ' + $("#classSelector").find(":selected").text() + 'and  level ' + selectedLevel, data);
      // data now contains the array of options for teacherSelector.
      // I'm going to assume you know how to loop through them and populate teacherSelector
    }
  });
});

冷却。现在,让我们来设置一个PHP脚本。我假设您正在使用MySQL数据库,对于此示例,我不会包含您需要使用的任何代码来清理和保护脚本(您可以在SO上找到所有其他问题)。大多数PHP脚本都是直接copy/paste from W3Schools

<?php
header('Content-Type: application/json'); // We are going to send a JSON response

// Server connection info
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$selectedValue = $_REQUEST['selectedValue'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM levels WHERE class = " . $selectedValue; // THIS IS AN EXAMPLE. IN PRODUCTION, ALWAYS CLEAN USER INPUT FIRST.
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  $results = array();
  while($row = $result->fetch_assoc()) {
    $results[] = $row;          
  }

  echo json_encode($results);
} else {
  echo json_encode("0 results");
}

$conn->close();