0

我正在开发这个小应用程序,但遇到了一个小问题。

我有 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/>
}
4

1 回答 1

4

使用 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 函数,如果您在主机上,可能已经安装了这些函数。

包括/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。假设您的日期表列称为“日期”和“日期描述”,您只需使用此代码

$.each(data.directors, function() {
    $("#date").append(
        // This actually appends the value on the date dropdown
        $("<option></option>").val(this.date).html(this.datedescription)
    )
})
于 2012-05-28T18:35:53.590 回答