javascript PHP Mysql - 如何使用javascript创建动态下拉列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15372174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:34:45  来源:igfitidea点击:

PHP Mysql - how to create a dynamic drop down list using javascript?

phpjavascriptmysql

提问by kev

I am totally new to scripting, basically i have to try and finish a school project on a coaching tour project. The idea is to allow customers to register and book a tour.

我对脚本编写完全陌生,基本上我必须尝试完成一个教练巡回项目的学校项目。这个想法是让客户注册和预订旅游。

What i am having problem with is, i have no idea on how to create a dynamic drop down list where the booking form will take the data from mysql database.

我遇到的问题是,我不知道如何创建一个动态下拉列表,其中预订表单将从 mysql 数据库中获取数据。

Lets say for example :

让我们说例如:

  1. The customer needs to select a choice of tour i.e (industrial, cultural, military) from the first drop down list.

  2. After selecting a tour, the next drop down list should list the destinations i.e. (UK, France, Germany, etc) dependant on the above (tour) choice.

  3. Then the third list should show the start dates dependant on the above (destination) choice.

  1. 客户需要从第一个下拉列表中选择一个旅游项目,即(工业、文化、军事)。

  2. 选择旅游后,下一个下拉列表应根据上述(旅游)选择列出目的地,即(英国、法国、德国等)。

  3. 然后第三个列表应显示取决于上述(目的地)选择的开始日期。

All the data in the drop down list should come from the database. Also when the customer submits the form, all those data should go into the customers booking table in the database.

下拉列表中的所有数据都应该来自数据库。同样,当客户提交表单时,所有这些数据都应该进入数据库中的客户预订表。

I was told that javascript should be the answer, but i have searched so many forums and look at tutorials which they are all confusing. Hence I came to ask here! Any help on how to do this is much appreciated. Thnx!

有人告诉我 javascript 应该是答案,但我搜索了很多论坛并查看了教程,它们都令人困惑。所以才来这里问的!非常感谢有关如何执行此操作的任何帮助。谢谢!

Below is the code of how i only know how to do this:

以下是我只知道如何执行此操作的代码:

           <h2><center>PLEASE PLACE YOUR BOOKING</center></h2>


<form action="booking.php" method="post">
<table width="700 border="0" align="center" cellpadding="0" cellspacing="0">
    <tr><td width="210" height="45">Tour Type:</td><td>
            <select name="tour_type">
            <option value="Cultural">Cultural</option>
            <option value="Industrial">Industrial</option>
            <option value="Military">Military</option>
     </select></td></tr>

    <tr><td width="210" height="45">Duration:</td><td>
            <select name="duration" >
            <option value="1_Day">1_Day</option>
            <option value="7_Days">7_Days</option>
            <option value="14_Days">14_Days</option>
        </select></td></tr>      

    <tr><td width="210" height="45">Destination:</td><td>
            <select name="destination" >
            <option value="England">England</option>
            <option value="Wales">Wales</option>
            <option value="Scotland">Scotland</option>
            <option value="France">France</option>
            <option value="Belgium">Belgium</option>
            <option value="Germany">Germany</option>
        </select></td></tr>

    <tr><td width="210" height="45">No. of Passengers:</td><td>
            <select name="no_of_passengers" >
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
        </select></td></tr>

    <tr><td width="210" height="45">Depature:</td><td>
            <select name="departure" >
            <option value="13 May 2013">13 May 2013</option>
            <option value="28 May 2013">28 May 2013</option>
            <option value="11 June 2013">11 June 2013</option>
            <option value="26 June 2013">26 June 2013</option>
            <option value="14 July 2013">14 July 2013</option>
            <option value="27 July 2013">27 July 2013</option>
        </select></td></tr>

    <tr><td width="210" height="45"><input type="checkbox" name="accomodation" 
     value="YES"/>Accomodation</td></tr>
    <tr><td width="210" height="45"><input type="checkbox" name="mailshot" 
    value="YES"/>Mailshot</td></tr>
    <tr><td width="210" height="45"><input type="submit" name="submit" value="submit"></td></tr>
    </table>
    </form>
</html>

    <?php
//When submit button is pressed.
if (isset($_POST['submit'])) {

//Include the server and database connection. 
include('cn.php');

session_start();

//retrieve data input from booking form and make it equal to the variable ($)
$tour_type = $_POST['tour_type'];
$duration = $_POST['duration'];
$destination = $_POST['destination'];
$no_of_passengers = $_POST['no_of_passengers'];
$departure = $_POST['departure'];

// accomodation confirmation
if (isset($_POST['accomodation'] ))
{$accom = $_POST["accomodation"];
} else {
$accom = "NO";
}

// mailshot confirmation
if (isset($_POST['mailshot'] ))
{$mail = $_POST["mailshot"];
} else {
$mail = "NO";
}

$userUsername = $_SESSION['loggedInUser'];

// Build the SQL query to retreive the variables ($) and input the data into the database.
$sql = "INSERT INTO booking 
      (user_id,tour_type,duration,destination,no_of_passengers,departure,accomodation,mailshot) 
VALUES ((SELECT user_id FROM user WHERE user_username = '" . 
       $userUsername . "'),'$tour_type','$duration','$destination',
       '$no_of_passengers','$departure','$accom' ,'$mail')";



// test the sql statement.
if(!mysql_query($sql,$cn)) {
die(mysql_error($cn));

}
// direct to this page when booking is successful.
header('Location: booking_success.php');
}

?>

回答by StenW

I had a similar issue. I found one guide that actually work and where he explains what he does. One thing that you should keep in mind when reading it though that it uses a different version of Jquery than the latest one, so there are a few differences in the syntax. These differences are minor though and can be found in the comments.

我有一个类似的问题。我找到了一个实际工作的指南,他解释了他的工作。尽管它使用的 Jquery 版本与最新版本不同,但在阅读它时您应该记住一件事,因此在语法上存在一些差异。这些差异虽然很小,但可以在评论中找到。

http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html

http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html

In your case it would look something like this:

在您的情况下,它看起来像这样:

SQL

查询语句

Create three tables one called id(Integer), one called master_id(Integer) and one called names(varchar).

创建三个表,一个叫做 id(Integer),一个叫做 master_id(Integer),一个叫做 names(varchar)。

Idis going to go from 1->x (meaning the last row is number x). master_idis going to be 0 for the items that is in the first drop down military etc. All of the items that you want to go in to the category military will have the same value of master_id as military has as id, for example 1. You follow this principal along with all the sub categories and dates. nameis just a label...

Id将从 1->x (意味着最后一行是数字 x)。 对于第一个下拉军事等中的项目,master_id将为 0。您想要进入军事类别的所有项目的 master_id 值将与军事具有相同的值,例如 1。您遵循此原则以及所有子类别和日期。名字只是一个标签……

Main site php/HTML

主站点 php/HTML

The Html would look something like this, where you put the script in the php in the head of your site.

Html 看起来像这样,您将脚本放在站点头部的 php 中。

?php
try {

 $objDb = new PDO('mysql:host=localhost;dbname=tour', 'root', 'root');
 $objDb->exec('SET CHARACTER SET utf8');

 $sql = "SELECT * 
  FROM `region`
  WHERE `master_id` = 0";
 $statement = $objDb->query($sql);
 $list = $statement->fetchAll(PDO::FETCH_ASSOC);

 } catch(PDOException $e) {
 echo 'There was a problem';
 }

 ?>

This is the forms.

这是表格。

    <select name="tour" id="tour" class="update">
        <option value="">Select one</option>
        <?php if (!empty($list)) { ?>
            <?php foreach($list as $row) { ?>
                <option value="<?php echo $row['id']; ?>">
                    <?php echo $row['name']; ?>
                </option>
            <?php } ?>
        <?php } ?>
    </select>

    <select name="location" id="location" class="update"
        disabled="disabled">
        <option value="">----</option>
    </select>

    <select name="date" id="date" class="update"
        disabled="disabled">
        <option value="">----</option>
    </select>

</form>

Remember to add the jquery and corect path to the ajax script.

记得在ajax脚本中添加jquery和corect路径。

PHP function

PHP函数

       <?php
  if (!empty($_GET['id']) && !empty($_GET['value'])) {

$id = $_GET['id'];
$value = $_GET['value'];

try {

    $objDb = new PDO('mysql:host=localhost;dbname=tour', 'root', 'password');
    $objDb->exec('SET CHARACTER SET utf8');

    $sql = "SELECT * 
            FROM `categories`
            WHERE `master` = ?";
    $statement = $objDb->prepare($sql);
    $statement->execute(array($value));
    $list = $statement->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($list)) {

        $out = array('<option value="">Select one</option>');

        foreach($list as $row) {
            $out[] = '<option value="'.$row['id'].'">'.$row['name'].'</option>';
        }

        echo json_encode(array('error' => false, 'list' => implode('', $out)));

    } else {
        echo json_encode(array('error' => true));
    }

} catch(PDOException $e) {
    echo json_encode(array('error' => true));
}

   } else {
echo json_encode(array('error' => true));
  }

ajax.js - the script

ajax.js - 脚本

     var formObject = {
run : function(obj) {
    if (obj.val() === '') {
        obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
    } else {
        var id = obj.attr('id');
        var v = obj.val();
        jQuery.getJSON('func/tour_function.php', { id : id, value : v }, function(data) {
            if (!data.error) {
                obj.next('.update').html(data.list).removeAttr('disabled');
            } else {
                obj.nextAll('.update').html('<option value="">----   </option>').attr('disabled', true);
            }
        });
    }
}
  };
  $(function() {

$('.update').on('change', function() {
    formObject.run($(this));
});

 });

Just remember to get the paths right and to include Jquery 1.9.1 and it should work.

请记住正确设置路径并包含 Jquery 1.9.1,它应该可以工作。

回答by David L

To point out an answer already on this site Ajax approach to populating a second dynamic dropdown based on the selection in the first

指出本网站上已有的答案 Ajax 方法根据第一个中的选择填充第二个动态下拉列表

Essentially, the short version would be an onchange event that loads data from your server

本质上,简短版本将是一个从服务器加载数据的 onchange 事件

<select name="first_dropdown" onchange="$('#dropdown2_container').load('your_script.php?nid='+this.value);">
    <option....
</select>
...
<div id="dropdown2_container" style="display:none"> </div>

I'm not a big fan of obtrusive javascript like this, but it's a start for you. If you want something a bit more elegant, try the following link.

我不是像这样突兀的 javascript 的忠实粉丝,但这对你来说是一个开始。如果您想要更优雅的东西,请尝试以下链接。

http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/

http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/

At least a bit of this should get you started.

至少有一点应该让你开始。

回答by mellamokb

There are a couple of approaches you can take. Since you are new to scripting, I would suggest avoiding AJAX at this point. You need something like the following:

您可以采用几种方法。由于您不熟悉脚本,因此我建议此时避免使用 AJAX。您需要类似以下内容:

  1. On the server-side (PHP), output the data into JavaScript variables that you can work with. For example, you could store the data in an array.

    Example: var tours = [{ id:1, name:"Tour#1" }, { id:2, name:"Tour#2" }, etc.]

  2. You'll want to load all tour data, destination data, and start dates into the script, with enough information to link which child records belong to which parent records.

  3. When the page first loads, the tour data should be populated into the first dropdown, but the second and third should be blank since they populate base on the previous ones.
  4. When the user makes a change to a dropdown value (onchangeevent), then apply the logic to load the entries to the next dropdown based on the selection in the previous dropdown.

    Example: <select id='tours' onchange='changetour();'></select>

  5. You'll also want to handle the situation where the user clears out a selection (clear out all the child selections in that case), or the user goes back to the first dropdown and changes their selection after they've already selected something in the second and third.

  1. 在服务器端 (PHP),将数据输出到您可以使用的 JavaScript 变量中。例如,您可以将数据存储在数组中。

    例子: var tours = [{ id:1, name:"Tour#1" }, { id:2, name:"Tour#2" }, etc.]

  2. 您需要将所有游览数据、目的地数据和开始日期加载到脚本中,并提供足够的信息来链接哪些子记录属于哪些父记录。

  3. 当页面第一次加载时,旅游数据应该填充到第一个下拉列表中,但第二个和第三个应该是空白的,因为它们基于前一个填充。
  4. 当用户对下拉值(onchange事件)进行更改时,然后应用逻辑以根据上一个下拉列表中的选择将条目加载到下一个下拉列表。

    例子: <select id='tours' onchange='changetour();'></select>

  5. 您还需要处理用户清除选择(在这种情况下清除所有子选择)的情况,或者用户在已经选择了某些内容后返回到第一个下拉列表并更改其选择第二和第三。

This should give you a rough idea of an algorithm to get started. I would suggest giving your best effort on each item above, and come back with specific questions after you've tried writing a solution and get stuck with a specific problem.

这应该让您对开始使用的算法有一个大致的了解。我建议您在上面的每个项目上尽最大努力,并在您尝试编写解决方案并遇到特定问题后回来提出特定问题。