簡體   English   中英

使用AJAX,PHP和MySQL鏈式填充HTML選擇框

[英]Chain populate HTML select boxes using AJAX, PHP and MySQL

我的特殊表格有兩個選擇框。 在頁面加載階段,我得到了第一個使用PHP的MySQL數據庫中的選項填充的對象。

我接下來要實現的目標是:

通過從第一個預填充的<select>框中選擇一個值,第二個<select>框將根據第一個<select>框中<select>選項從數據庫表中填充相關數據。

因此,如下圖所示,如果我從第一個<select>框中選擇一個位置,則第二個<select>框中將填充該位置上的所有套件。

在此處輸入圖片說明

我的數據庫已經准備好所有數據並建立了關系。 我已經在數據庫端測試了我的SQL查詢,它們可以工作。 現在,我需要將所有內容放入一個PHP腳本中,該腳本將通過表單中的AJAX調用進行調用。

到目前為止,我所做的是嘗試將$.ajax請求從此表單發送到名為jQueryHelper.php的PHP腳本,而該腳本又應返回套件,我將在開始時使用alert()

jQueryHelper.php:

<?php
define("DB_HOST", "127.0.0.1");
define("DB_NAME", "mydb");
define("DB_USER", "root");
define("DB_PASS", "**********");

class jQueryHelper
{
    private static $initialized = false;
    private $db_connection = null;

    private static function initialize()
    {
        if (self::$initialized)
            return;
        $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        self::$initialized = true;
    }

    public static function giveData()
    {
        self::initialize();
        if (!$this->db_connection->set_charset("utf8")) {
            $this->errors[] = $this->db_connection->error;
        }
        if (!$this->db_connection->connect_errno) {
                if(isset($_POST['action']) && !empty($_POST['action'])){
                    $action = $_POST['action'];
                    $theSelectedLocationId = $_POST['id'];
                    switch($action){
                        case 'getAssignedSuites': 
                            $this->getAssignedSuites($theSelectedLocationId);
                            break;
                    }
                }
        }
    }

    public static function getAssignedSuites($theSelectedLocationId){
        $sql =<<<EOF
            SELECT * FROM suites
            WHERE location_id = $theSelectedLocationId
EOF;

        $query_get_assigned_suites = $this->db_connection->query($sql);
        $rows = array();
        while($r = mysqli_fetch_assoc($query_get_assigned_suites)){
            $rows[] = $r;
        }
        echo json_encode($rows);
    }
}

// Call it!
jQueryHelper::giveData();
?>

HTML形式:

<form method="post" action="user_todays_locations.php" name="updatetodayslocation" role="form">
    <div class="form-group">
        <label for="suite_location" class="sr-only">Assigned Locations</label>
        <select size="1" name="suite_location" class="form-control input-lg" required>
            <option value="" selected="selected" disabled>Assigned Locations</option>
            <?php $location->getAssignedLocations($login->getCurrentUserID()); ?>
        </select>
    </div>
    <!-- more divs and form controls here -->
</form>

jQuery的$.ajax (位於<form>上方的<form> <body> <form> ):

<script>
// grab ID of selected location
$(function() {
    $("select[name=suite_location]").change(function() {
        var theSelectedLocationId = this.value;
        //alert(theSelectedLocationId);
        $.ajax({ url: '/classes/jQueryHelper.php',
            data: {action: 'getAssignedSuites', id: theSelectedLocationId},
            type: 'post',
            success: function(output) {
                alert(output);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                if (jqXHR.status === 0) {
                    alert('Not connect.\n Verify Network.');
                } else if (jqXHR.status == 404) {
                    alert('Requested page not found. [404]');
                } else if (jqXHR.status == 500) {
                    alert('Internal Server Error [500].');
                } else if (exception === 'parsererror') {
                    alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                    alert('Time out error.');
                } else if (exception === 'abort') {
                    alert('Ajax request aborted.');
                } else {
                    alert('Uncaught Error.\n' + jqXHR.responseText);
                }
            }
        });
});
</script>

jQuery的<select> .change事件毫無問題地觸發,並且我收到一個帶有選定選項值的警報(在我的情況下,這是數據庫中位置的ID)。 $.ajax部分嵌套得更深,它不想工作。 整個網站都存儲在LAMP服務器上。 整個網站都位於: /mywebsites/project/www/表單位於views文件夾內,該文件夾與其他視圖一起顯示在根目錄的腳本中,以顯示完整的頁面。 jQueryHelper.php位於classes文件夾內。

我不知道,也許有更簡單的方法可以做到這一點。

在您的switch塊中,您是否不應該返回getAssignedSuites調用返回的結果?

switch($action){
  case 'getAssignedSuites': 
    return $this->getAssignedSuites($theSelectedLocationId);
    break;
}

然后按照@sean的建議。 echo jQueryHelper::giveData();

也。 我不認為在類函數中調用$_POST是一個好習慣。 我建議將它們作為像jQueryHelper::giveData($_POST['action'], $_POST['id'])類的參數傳遞jQueryHelper::giveData($_POST['action'], $_POST['id'])然后使用它。

AJAX調用找不到jQueryHelper.php url/classes/jQueryHelper.php更改為classes/jQueryHelper.php解決路徑問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM