PHP动态下拉HTML菜单解析到第二个动态菜单问题

kpbwa7wx  于 2023-03-07  发布在  PHP
关注(0)|答案(1)|浏览(119)

我一直在尝试建立一个动态菜单,传递到另一个菜单,就像旧的[国家]〉〉[城市]场景,但不是我到底在做什么。
但从我所遵循的我似乎有一个错误的地方。我可以看到下拉菜单。第一说[加载...]和第二说[选择零件号]
因此,从我所看到的,这是卡住了从1form.php文件拉信息,所以我一直在看这几天,没有进一步前进,有人能解释一下我做错了什么吗?
NB:消极情绪不能帮助人们学习!

1form.php
-------------
<?php
include 'process/database.php';
include 'header.php'; // this includes the session_start();
//if ($_SESSION == false) {
//    header('location: login.php?status=notloggedin');
//}

$sql = mysqli_query($conn, "SELECT * FROM `custcode` ORDER BY `ID2` ASC");
if(mysqli_num_rows($sql)) {
    $data = array();
    while($row = mysqli_fetch_array($sql)) {
        $data[] = array(
            'ID1'       => $row['ID1'],
            'ID2'       => $row['ID2'],
            'ENABLED2'  => $row['ENABLED2'],
            'SOLDTO2'   => $row['SOLDTO2']
        );
    }
    header('Content-type: application/json');
    echo json_encode($data);
}
?>


2form.php
-------------
<?php
include 'process/database.php';
include 'header.php'; // this includes the session_start();
//if ($_SESSION == false) {
//    header('location: login.php?status=notloggedin');
//}

$sql = mysqli_query($conn, "SELECT * FROM partnumbers WHERE ID1='".$_GET["ID1"]."'");
if(mysqli_num_rows($sql)) {
    $data = array();
    while($row = mysqli_fetch_array($sql)) {
        $data[] = array(
            'id'            => $row['id'],
            'partnumber'    => $row['partnumber'],
            'disabled1'     => $row['disabled1'],
            'tiedto'        => $row['tiedto']
        );
    }
    header('Content-type: application/json');
    echo json_encode($data);
}
?>

3form.php where it should take place
----------------------------------------
<?php
include 'process/database.php';
include 'header.php';
//if ($_SESSION == false) {
//    header('location: login.php?status=notloggedin');
//}
?>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/JavaScript">

        function customer(){
    $('#firstDDLModel').empty();
    $('#firstDDLModel').append("<option>Loading......</option>");
    $('#secondDDLModel').append("<option value='0'>--Select Part Number--</option>");
    $.ajax({
        type:"POST",
        url:"1form.php",
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success: function(data) {
            $('#firstDDLModel').empty();
            $('#firstDDLModel').append("<option value='0'>--Select Customer--</option>");
            $.each(data,function(i,item) {
                $('#firstDDLModel').append('<option value="'+ data[i].ID1 +'">'+ data[i].ID1+'</option>');
            });            
        },
        complete: function() {
        }
    });
}

function part(ID1){
    $('#secondDDLModel').empty();
    $('#secondDDLModel').append("<option>Loading......</option>");
    $.ajax({
        type:"POST",
        url:"2form.php?ID1="+ID1,
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success: function(data) {
            $('#secondDLModel').empty();
            $('#secondDDLModel').append("<option value='0'>--Select Customer--</option>");
            $.each(data,function(i,item) {
                $('#secondDDLModel').append('<option value="'+ data[i].ID1 +'">'+ data[i].partnumber+'</option>');
            });            
        },
        complete: function() {
        }
    });
}

$(document).ready(function(){
    customer();
    $("#firstDDLModel").change(function() {
        var ID1 = $("#firstDDLModel").val();
        part(ID1);
    });
});
</script>
</head>

<body>
    <span>Customer</span>
    <select id="firstDDLModel"></select>
    <span>Part</span>
    <select id="secondDDLModel"></select>
</body>
</html>

基本形式的DB是

CUSTCODE
+-----+------+-----------+----------+
| ID1 | ID2  |  SOLDTO2  | ENABLED2 |
+-----+------+-----------+----------+
|  5  | AA01 | Mr Smith  | 0        |
|  6  | DF06 | Mrs Jones | 0        |
+-----+------+-----------+----------+

PARTNUMBERS
+-------+------------+-----------+-----------+-----------------------+
|  ID   | partnumber | partdesc  | disabled1 | ID1 (fk custcode:ID1) |
+-------+------------+-----------+-----------+-----------------------+
|  101  | Part001    | a shoe    | 0         | 5                     |
|  102  | Part030    | a dog     | 0         | 6                     |
+-------+------------+-----------+-----------+-----------------------+
aor9mmx1

aor9mmx11#

我再次查看了您的代码,在数据库中创建了几个测试表,并尝试让您的代码正常工作。
AJAX 请求发送POST请求,但是你的PHP在构造第二个下拉菜单时需要一个GET变量。ajax请求还包含contentType:"application/json; charset=utf-8",这导致(对我来说)请求完全失败,所以这些请求被删除,并使用data参数代替querystring。
给定一个如下所示的测试方案:

mysql> describe custcode;
+----------+---------------------+------+-----+---------+----------------+
| Field    | Type                | Null | Key | Default | Extra          |
+----------+---------------------+------+-----+---------+----------------+
| ID1      | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |
| ID2      | varchar(6)          | NO   |     | NULL    |                |
| SOLDTO2  | varchar(32)         | NO   |     | NULL    |                |
| ENABLED2 | tinyint(1) unsigned | NO   |     | 1       |                |
+----------+---------------------+------+-----+---------+----------------+
4 rows in set (0.05 sec)

mysql> select * from custcode;
+-----+------+-----------+----------+
| ID1 | ID2  | SOLDTO2   | ENABLED2 |
+-----+------+-----------+----------+
|   1 | aa01 | mr smith  |        1 |
|   2 | fd83 | mrs smith |        0 |
+-----+------+-----------+----------+
2 rows in set (0.00 sec)



mysql> describe partnumbers;
+------------+---------------------+------+-----+---------+----------------+
| Field      | Type                | Null | Key | Default | Extra          |
+------------+---------------------+------+-----+---------+----------------+
| ID         | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |
| PARTNUMBER | varchar(50)         | NO   |     | 0       |                |
| PARTDESC   | varchar(50)         | NO   |     | 0       |                |
| DISABLED1  | tinyint(1) unsigned | NO   |     | 0       |                |
| ID1        | int(10) unsigned    | NO   | MUL | NULL    |                |
+------------+---------------------+------+-----+---------+----------------+
5 rows in set (0.06 sec)

mysql> select * from partnumbers;
+-----+------------+----------+-----------+-----+
| ID  | PARTNUMBER | PARTDESC | DISABLED1 | ID1 |
+-----+------------+----------+-----------+-----+
| 101 | part001    | a shoe   |         0 |   1 |
| 102 | part002    | turtle   |         1 |   2 |
+-----+------------+----------+-----------+-----+
2 rows in set (0.00 sec)

并修改了PHP/HTML和Javascript

<?php
    error_reporting( E_ALL );
    
    /* 
        Include database connection.
        Obviously this will be different for you.
    */
    chdir('../../dbo');
    require 'db-conn-details.php';
    require 'mysqli-conn.php';
    
    
    
    /*
        Process POST requests made by AJAX calls.
        Rather than multiple files, a single script is used
        to process all requests.
        
        Also, a `Prepared Statement` is used to mitigate SQL injection
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
        
        $args=array();
        
        switch( $_POST['action'] ){
            case 'fetch-customer':
                $sql='SELECT * FROM `custcode` ORDER BY `ID2` ASC';
            break;
            case 'fetch-part':
                $sql='SELECT * FROM partnumbers WHERE ID1=?';
                $args[]=$_POST['id'];
            break;
        }
        
        $stmt=$db->prepare( $sql );
        if( !empty( $args )){
            $types=str_repeat( 's', count( $args ) );
            $stmt->bind_param( $types,...$args );
        }
        
        $stmt->execute();
        $res=$stmt->get_result()->fetch_all( MYSQLI_ASSOC );
        
        header('Content-Type: application/json');
        exit( json_encode( $res ) );
    }
    
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <script src='//code.jquery.com/jquery-latest.js'></script>
    </head>
    <body>
    
    
        <span>Customer</span>
        <select id="firstDDLModel"></select>
        <span>Part</span>
        <select id="secondDDLModel"></select>
        
        
        <script>
            function customer() {
              $('#firstDDLModel').empty();
              $('#firstDDLModel').append("<option>Loading......</option>");
              $('#secondDDLModel').append("<option value='0'>--Select Part Number--</option>");
              /*
                POST requests do NOT send data in the querystring
                but rather it is within the body so use the `data`
                argument for the ajax request as below.
                
                The "action" parameter allows the PHP to differentiate
                the request and process the appropriate SQL query.
              */
              $.ajax({
                type: "POST",
                url: location.href,
                data:{ 
                    action:'fetch-customer'
                },
                success: function(data) {
                  $('#firstDDLModel').empty();
                  $('#firstDDLModel').append("<option value='0'>--Select Customer--</option>");
                  $.each(data, function(i, item) {
                    $('#firstDDLModel').append('<option value="' + data[i].ID1 + '">' + data[i].ID1 + '</option>');
                  });
                },
                complete:()=>console.log('ok'),
                error:(err)=>alert(err)
              });
            }

            function part(ID1) {
              $.ajax({
                type: "POST",
                url: location.href,
                data:{ 
                    action:'fetch-part',
                    id:ID1 
                },
                success: function(data) {
                  $('#secondDLModel').empty();
                  $.each(data, function(i, item) {
                    $('#secondDDLModel').append('<option value="' + data[i].ID1 + '">' + data[i].PARTNUMBER + '</option>');
                  });
                },
                complete:()=>console.log('ok'),
                error:(err)=>alert(err)
              });
            }

            $(document).ready(function() {
              customer();
              $("#firstDDLModel").change(function() {
                var ID1 = $("#firstDDLModel").val();
                part(ID1);
              });
            });
        </script>
    </body>
</html>

相关问题