php,ajax,html select元素


                    

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

我有3个下拉菜单( name </ code>, date </ code>和 path </ code>)。
用户将选择一个名称,然后该用户的日期应显示在日期下拉菜单中。
然后,用户选择一个日期,然后路径名将显示在相应的下拉菜单中。
然后,用户选择一条路径,此时会发生其他无关紧要的事情。</ p>

我在服务器端使用PHP(我对此非常满意),而我基本上没有经验的javascript / ajax。 据我了解,我需要使用AJAX技术,这样就不必重新加载整个页面,而对于那些下拉菜单也不需要这样。</ p>

我已经生成了名称下拉菜单,但是很难弄清楚如何处理日期和路径。</ p>

现在,我有一些简单的吸气剂(下面是其中的一种),我认为这些吸气剂可以帮助我完成我要完成的工作(如果不能帮忙,请纠正我)。 我也一直在阅读有关AJAX的书并在互联网上进行研究,但还没有发现其他任何东西。 感谢您的帮助。</ p>

  function getName(){

     var nameSelect = document.getElementById(“ names”);

     var selectedName = nameSelect.options [nameSelect.selectedIndex] .text;

     返回selectedName;

}
</ code> </ pre>
     </ div>

展开原文

原文

I'm working on this little app and I have reached a small issue.

I have 3 drop-down menus (name, date, and path). The user is to select a name, then the dates for that user should show up in the date drop-down menu. Then the user selects a date, and then the path names are to show up in the corresponding drop-down menu. The user then selects a path, and other stuff happens which doesn't matter at this point.

I'm using PHP on the server side (which I am decently comfortable with) and javascript/ajax I have basically no experience with. To my understanding I need to use AJAX techniques so the whole page doesn't have to reload and whatnot for those drop-downs.

I have the names drop-down menu generated, but am having a hard time figuring out how to do the date and path ones.

Right now I have some simple getters (one of them is below) which I think may help me with what I'm trying to accomplish (correct me if those will not help). I have also been reading a book on AJAX and researching on the internet, but have not figured out anything else. Any help is appreciated.

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

1个回答

Use jQuery, it'll help you forget about browsers and focus on coding alone.

Assume this is your HTML and 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>

You'd need a PHP file, which outputs the data like the following:

<?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);
}

I couldn't test it, but hopefully it gives you an idea on AJAX and jQuery. Also have a look at jQuery Documentations and the API reference, which explains available methods and options.

Update: You're not bound to use value and label as the array key name. But if you want to, you could create a query which looks like this (this is a PDO example, you might want to get into PDO, since it saves you the hassle of escaping input, and makes recurring queries easier). This will require the PDO functions for PHP, which might be already installed if you're on a hoster.

includes/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();
    }
}

?>

And in your api.php you'd go like this

<?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());
}

But as I said, you might also change the jQuery code, so your columns don't have to be named value and label. Assuming you're table columns for the date are called "date" and "datedescription", you'd just use this code

$.each(data.directors, function() {
    $("#date").append(
        // This actually appends the value on the date dropdown
        $("<option></option>").val(this.date).html(this.datedescription)
    )
})
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐