복붙노트

동적 드롭 다운 상자?

PHP

동적 드롭 다운 상자?

다음과 같이 category라는 데이터베이스 테이블이 있습니다.

내가 동적 드롭 다운 상자를하려고하고 색인 스크립트로 표시됩니다 :

<?php

try {

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

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

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

    ?>
    <!DOCTYPE HTML>
   <html lang="en">
   <head>
<meta charset="utf-8" />
<title>Dependable dropdown menu</title>
<meta name="description" content="Dependable dropdown menu" />
<meta name="keywords" content="Dependable dropdown menu" />
<link href="/css/core.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="/js/jquery-1.6.4.min.js" type="text/javascript"></script>
  <script src="/js/core.js" type="text/javascript"></script>
  </head>
  <body>

  <div id="wrapper">

<form action="" method="post">

    <select name="gender" id="gender" 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="category" id="category" class="update"
        disabled="disabled">
        <option value="">----</option>
    </select>

    <select name="colour" id="colour" class="update"
        disabled="disabled">
        <option value="">----</option>
    </select>       
</form>
</div>
</body>
</html>

update.php는 다음과 같이 표시됩니다 :

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

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

try {

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

    $sql = "SELECT * 
            FROM `category`
            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));
}

두 번째 드롭 다운 상자는 다음과 같이 첫 번째 드롭 다운 상자에 종속 된 값을 표시하지 않습니다.

누군가 제발 나를 도울 수 있습니까?

해결법

  1. ==============================

    1.당신이 원하는 것을 할 수있는 예제가 있습니다. 기본적으로 jQuery / AJAX를 사용하여이를 수행 할 수 있습니다.

    당신이 원하는 것을 할 수있는 예제가 있습니다. 기본적으로 jQuery / AJAX를 사용하여이를 수행 할 수 있습니다.

    서버 로그인 / 테이블 / 필드 이름과 일치하도록 예제 코드를 업데이트 했으므로이 두 예제를 파일 (tester.php 및 another_php_file.php라고 함)에 복사 / 붙여 넣는 경우 완전히 연주 할 수있는 예제가 있어야합니다.

    아래의 예제를 수정하여 두 번째 드롭 다운 상자를 만들고 값을 채 웁니다. 논리를 한 행씩 따라하면 실제로는 매우 간단합니다. 주석을 달지 않은 여러 줄을 남겨 두었다. 주석을 제거하면 (한 번에 하나씩) 각 단계에서 스크립트가 수행하는 작업이 표시됩니다.

    파일 1 - 검사자 .PHP

    <html>
        <head>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script type="text/javascript">
                $(function() {
    //alert('Document is ready');
    
                    $('#stSelect').change(function() {
                        var sel_stud = $(this).val();
    //alert('You picked: ' + sel_stud);
    
                        $.ajax({
                            type: "POST",
                            url: "another_php_file.php",
                            data: 'theOption=' + sel_stud,
                            success: function(whatigot) {
    //alert('Server-side response: ' + whatigot);
                                $('#LaDIV').html(whatigot);
                                $('#theButton').click(function() {
                                    alert('You clicked the button');
                                });
                            } //END success fn
                        }); //END $.ajax
                    }); //END dropdown change event
                }); //END document.ready
            </script>
        </head>
    <body>
    
        <select name="students" id="stSelect">
            <option value="">Please Select</option>
            <option value="John">John Doe</option>
            <option value="Mike">Mike Williams</option>
            <option value="Chris">Chris Edwards</option>
        </select>
        <div id="LaDIV"></div>
    
    </body>
    </html>
    

    파일 2 - another_php_file.php

    <?php
    
    //Login to database (usually this is stored in a separate php file and included in each file where required)
        $server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
        $login = 'root';
        $pword = '';
        $dbname = 'test';
        mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
        mysql_select_db($dbname) or die($connect_error);
    
    //Get value posted in by ajax
        $selStudent = $_POST['theOption'];
        //die('You sent: ' . $selStudent);
    
    //Run DB query
        $query = "SELECT * FROM `category` WHERE `master` = 0";
        $result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
        $num_rows_returned = mysql_num_rows($result);
        //die('Query returned ' . $num_rows_returned . ' rows.');
    
    //Prepare response html markup
        $r = '  
                <h1>Found in Database:</h1>
                <select>
        ';
    
    //Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
        if ($num_rows_returned > 0) {
            while ($row = mysql_fetch_assoc($result)) {
                $r = $r . '<option value="' .$row['id']. '">' . $row['name'] . '</option>';
            }
        } else {
            $r = '<p>No student by that name on staff</p>';
        }
    
    //Add this extra button for fun
        $r = $r . '</select><button id="theButton">Click Me</button>';
    
    //The response echoed below will be inserted into the 
        echo $r;
    

    "두 번째 드롭 다운 상자가 첫 번째 드롭 다운 상자에서 선택한 옵션에만 관련된 필드를 어떻게 채우게합니까?"

    A. 첫 번째 드롭 다운의 .change 이벤트 내부에서 첫 번째 드롭 다운 상자의 값을 읽습니다.

    $ ( '# dropdown_id'). change (function () {         var dd1 = $ ( '# dropdown_id') .Val ();     }

    B. 위의 .change () 이벤트에 대한 AJAX 코드에서 두 번째 .PHP 파일로 보내는 데이터에 해당 변수를 포함합니다 (이 경우 "another_php_file.php").

    C. mysql 쿼리에서 전달 된 변수를 사용하므로 결과가 제한됩니다. 이 결과는 AJAX 함수로 전달되며 AJAX 함수의 성공 부분에서 액세스 할 수 있습니다.

    D. 성공 함수에서 수정 된 SELECT 값을 사용하여 코드를 DOM에 삽입합니다.

    이것이 위의 예제에서 제가하고있는 것입니다 :

    이제 첫 번째 드롭 다운 컨트롤에서 선택한 값과 관련된 값으로 사용자 정의 된 두 번째 드롭 다운 컨트롤이 나타납니다.

    비 Microsoft 브라우저처럼 작동합니다.

  2. from https://stackoverflow.com/questions/16924082/dynamic-drop-down-box by cc-by-sa and MIT license