簡體   English   中英

php,ajax,html select元素

[英]php, ajax, html select element

我正在開發這個小應用程序,但遇到了一個小問題。

我有3個下拉菜單( namedatepath )。 用戶將選擇一個名稱,然后該用戶的日期應顯示在日期下拉菜單中。 然后,用戶選擇一個日期,然后路徑名將顯示在相應的下拉菜單中。 然后,用戶選擇一條路徑,此時發生其他無關緊要的事情。

我在服務器端使用PHP(我對此非常滿意),而我基本上沒有經驗的javascript / ajax。 據我了解,我需要使用AJAX技術,這樣就不必重新加載整個頁面,而對於那些下拉菜單也不需要這樣。

我已經生成了名稱下拉菜單,但是很難弄清楚如何處理日期和路徑。

現在,我有一些簡單的吸氣劑(下面是其中的一種),我認為這些吸氣劑可以幫助我完成我要完成的工作(如果不能幫忙,請糾正我)。 我也一直在讀一本關於AJAX的書並在互聯網上進行研究,但沒有發現其他問題。 任何幫助表示贊賞。

function getName(){<br/>
    var nameSelect = document.getElementById("names");<br/>
    var selectedName = nameSelect.options[nameSelect.selectedIndex].text;<br/>
    return selectedName;<br/>
}

使用jQuery,它將幫助您忘記瀏覽器,而只專注於編碼。

假設這是您的HTML和Javascript

<html>
<head>
    <title>Dropdowns</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
        // Detect if a change to the name dropdown is made
        $("#name").change(function() {

        // Setup the AJAX call (this is a call which expects JSON as response)
        $.ajax({
            url: "http://example.com/api.php",
            type: "json",                        
            // Specify the GET parameter "name" with the value from the name dropdown
            data: {
                name: $("#name").val()
            },

            // If AJAX was successfull add the regarding values to the date dropdown
            success: function() {               
                // The response from PHP contains an array encoded in JSON.
                // This means, we have to loop trough the results
                $.each(data.directors, function() {
                    $("#date").append(
                        // This actually appends the value on the date dropdown
                       $("<option></option>").val(this.value).html(this.label)
                    )
                });
            }
       });

       // Detect if a change to the date dropdown is made
       $("#date").change(function() {

       // Setup the AJAX call (this is a call which expects JSON as response)
       $.ajax({
           url: "http://example.com/api.php",
           type: "json",
           // Specify the GET parameter "date" with the value from the date dropdown
           data: {
               date: $("#date").val()
           },

           // If AJAX was successfull add the regarding values to the path dropdown
           success: function() {

              // The response from PHP contains an array encoded in JSON. This means, we have to loop trough the results
              $.each(data.directors, function() {
                   $("#path").append(
                       // This actually appends the value on the path dropdown
                       $("<option></option>").val(this.value).html(this.label);
                   )
               });
           }
     });
    </script>
</head>

<body>
   <form name="someform">
       <select name="name" id="name">
           <option value="1">John Smith</option>
           <option value="2">Peter Johnson</option>
       </select>

       <select name="date" id="data">
           <option value=""></option>
       </select>

       <select name="path" id="data">
           <option value=""></option>
       </select>
   </form>
</body>
</html>

您需要一個PHP文件,該文件輸出如下數據:

<?php
if($_GET['name'] != "" && isset($_GET['name'])) {
    // Now you'd need some logic to generate an array, containing the information for this name
    // We'll just create one manually now

    $dates = array();

    $dates[]['value'] = "349876973";
    $dates[]['label'] = "Date description 1";
    $dates[]['value'] = "783693876";
    $dates[]['label'] = "Date description 2";

    echo json_encode($dates);
} elseif($_GET['date'] != "" && isset($_GET['date'])) {
    // Now you'd need some logic to generate an array, containing the information for this date
    // We'll just create one manually now

    $paths = array();

    $dates[]['value'] = "path value 1";
    $dates[]['label'] = "Path description 1";
    $dates[]['value'] = "path value 2";
    $dates[]['label'] = "Path description 2";

    echo json_encode($paths);
}

我無法對其進行測試,但希望它能使您對AJAX和jQuery有所了解。 還可以查看jQuery文檔和API參考,其中介紹了可用的方法和選項。

更新:您不必將value和label用作數組鍵名。 但是,如果願意,您可以創建一個如下所示的查詢(這是一個PDO示例,您可能想進入PDO,因為它節省了轉義輸入的麻煩,並使重復查詢更容易)。 這將需要用於PHP的PDO函數 ,如果您在托管服務器上,則可能已經安裝了PDO函數

包括/ db.include.php

<?php
class example {
    // Create database connection
    public function __construct() {
        $this->db = new PDO("pgsql:host=localhost;dbname=exampledb;", "user", "password");
        if(!$this->db) {
            die("Connection failed!");
        }
    }

    // Get dates
    public function getDates($name) {
        $sql = "SELECT
                    date AS value, datedescription AS label
                FROM
                    some_table
                WHERE
                    name = ?";

        $stmt = $this->db->prepare($sql);

        $stmt->bindParam(1, $name);

        if(!$stmt->execute()) {
            // Only for debugging, wouldn't use this on production
            var_dump($stmt->errorInfo());
        }

        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $result;
    }

    // Get paths
    public function getPaths($date) {
        $sql = "SELECT
                    path AS value, pathdescription AS label
                FROM
                    another_table
                WHERE
                    date = ?";

        $stmt = $this->db->prepare($sql);

        $stmt->bindParam(1, $date);

        if(!$stmt->execute()) {
            // Only for debugging, wouldn't use this on production
            var_dump($stmt->errorInfo());
        }

        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $result;
    }

    // Close database connection
    public function __destruct() {
        @$this->db->close();
    }
}

?>

在您的api.php中,您將像這樣

<?php
include 'includes/db.include.php';

$example = new example;

if(isset($_GET['name'])) {
    echo json_encode($example->getDates($_GET['name']));
} elseif(isset($_GET['date'])) {
    echo json_encode($example->getPaths());
}

但是正如我所說,您可能還會更改jQuery代碼,因此不必將列命名為value和label。 假設您在日期的表列稱為“ date”和“ datedescription”,則只需使用此代碼

$.each(data.directors, function() {
    $("#date").append(
        // This actually appends the value on the date dropdown
        $("<option></option>").val(this.date).html(this.datedescription)
    )
})

暫無
暫無

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

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