HTML形式的“尝试访问类型为null的值的数组偏移量”

问题描述

我创建了一个HTML表单,其中的文本框链接一个下拉列表。当我在文本框中输入邮政编码时,应在右侧的下拉列表中填充相应的国家/地区。

相反,我变成了错误

尝试访问类型为null的值中的数组偏移量 /var/www/html/index.PHP,第58行,引荐网址:http://127.0.0.1/html/

这是我的代码

<!DOCTYPE html>
<html lang="fr">
    <head>
        <Meta charset="utf-8">
        <title>Listes li&eacute;es en JQuery</title>
        <link rel="shortcut icon" href="../../../images/site/favicon.ico" />
        <link type="text/css" rel="stylesheet" href="css/style.css" />
        
        <!-- Linked Lists -->
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/jquery.chained.js"></script>
        
        <!-- Updating departements -->
        <script type="text/javascript">
            $(function(){
            $("#departement").chained("#region");
            });
        </script>
        
        <!-- Updating communes -->
        <script type="text/javascript">
            $(function(){
            $("#commune").chained("#codepostal");
            });
        </script>
</head>

<body>
<?PHP
        // Connecting to database
        $bddname = 'database';
        $hostname = 'localhost';
        $username = 'user';
        $password = 'pass';
        $db = MysqLi_connect ($hostname,$username,$password,$bddname);
        $db -> set_charset("utf8");
?>

<form method="post">
    <select name="region" id="region">
        <option value="">Sélectionner une région</option>
        <?PHP
            // Call up regions and display them in dropdown list
            $req = "SELECT RegionId,Nomregion FROM regions ORDER BY Nomregion";        
            $rep = MysqLi_query($db,$req);
            while ($row = MysqLi_fetch_array($rep)) {
                echo "<option value=".$row['RegionId'].">".$row['Nomregion']."</option>";
            }
        ?>
    </select>

    <select name="departement" id="departement">
        <option value="">Sélectionner un département</option>
        <?PHP
            // Call up departments and display them in dropdown list
            $req = "SELECT DepartementId,RegionId,NomDepartement FROM departements ORDER BY NomDepartement";
            $rep = MysqLi_query($db,$req);
            while ($row = MysqLi_fetch_array($rep)) {
                echo "<option value=".$row['DepartementId']." class=".$row['RegionId'].">".$row['NomDepartement']."</option>";
            }
        ?>
    </select>

     <!-- Zip Code TextBox -->  
     <input type="text" name="codepostal" id="codepostal" value="<?PHP $row['CodePostal']; ?>">
            
     <select name="commune" id="commune">
        <option value="">Sélectionner une commune</option>
        <?PHP
            // Call up countries and display them in dropdown list
            $req = "SELECT NomCommune FROM communes;
                            LEFT JOIN communeCP;
                            ON communeCP.CommuneId = communes.CommuneId;
                            LEFT JOIN codesPostaux;
                            ON codesPostaux.CodePostalId = communeCP.CodePostalId;
                            WHERE codesPostaux.CodePostal = ".$row["CodePostal"]." ORDER BY NomCommune";
            $rep = MysqLi_query($db,$req);
            while ($row = MysqLi_fetch_array($rep)) {
                echo "<option value=".$row['communeId']." class=".$row['CodePostal'].">".$row['NomCommune']."</option>";
            }
        ?>
    </select>
    
</form>

</body>
</html>

解决方法

使用jquery更改eventListener。

$('#codepostal').on('change',fnuction(evt){
   $('#commune').html(mockCommuneOptions());
})

//return mock options
function mockCommuneOptions(){
  const options = ['a','b','c']
  let optiionsStr = '';
  options.forEach(option => {
    optiionsStr += `<option value='${option}'>${option}</option`;
  });

return optiionsStr;
}
,

因此,请使用AJAX对其进行测试。知道,我的脚本可以正常运行,而apache2日志中没有任何错误。但是,它在输入框和右手列表框之间显示[],当我输入邮政编码时什么也没发生。

代码如下:

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
    <title>Listes li&eacute;es en JQuery</title>
    <link rel="shortcut icon" href="../../../images/site/favicon.ico" />
    <link type="text/css" rel="stylesheet" href="css/style.css" />
     
    <!-- Linked Lists -->        
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/jquery.chained.js"></script>
      
    <!-- Updating departements -->
    <script type="text/javascript">
        $(function(){
            $("#departement").chained("#region");
        });
    </script>
      
</head>
 
    <body>
    <?php
        // Connecting to database
        $bddname = 'database';
        $hostname = 'localhost';
        $username = 'user';
        $password = 'pass';
        $db = mysqli_connect ($hostname,$username,$password,$bddname);
        $db -> set_charset("utf8");
    ?>
            
    <form method="post">
        <select name="region" id="region">
            <option value="">Sélectionner une région</option>
                <?php
                    // Call up regions and display them in dropdown list
                    $req = "SELECT RegionId,NomRegion FROM regions ORDER BY NomRegion";        
                    $rep = mysqli_query($db,$req);
                    while ($row = mysqli_fetch_array($rep)) {
                        echo "<option value=".$row['RegionId'].">".$row['NomRegion']."</option>";
                    }
                ?>
            </select>
            
            <select name="departement" id="departement">
                <option value="">Sélectionner un département</option>
                <?php
                    // Call up departments and display them in dropdown list
                    $req = "SELECT DepartementId,RegionId,NomDepartement FROM departements ORDER BY NomDepartement";
                    $rep = mysqli_query($db,$req);
                    while ($row = mysqli_fetch_array($rep)) {
                        echo "<option value=".$row['DepartementId']." class=".$row['RegionId'].">".$row['NomDepartement']."</option>";
                    }
                ?>
            </select>
 
            <!-- Zip Code Textbox -->
            <input type="text" name="codepostal" id="codepostal" pattern="[0-9]*" maxlength="5">
            
                <!-- Call up countries to display them in dropdown list -->
                <script type="text/javascript">
                    $(document).ready(function(){
                        $("#codepostal").blur(function(){
                            var cp = $(this).val();
                            $.ajax({
                                type: 'post',data: {codePostal:cp},dataType: 'json',success:function(response){
                                    var len = response.length;
                                    $("#commune").empty();
                                    for( var i = 0; i<len; i++ ){
                                        var id = response[i]['id'];
                                        var name = response[i]['name'];
                                        $("#commune").append("<option value='"+id+"'>"+name+"</option>");
                                    }
                                }
                            });
                        });
                    });
                </script>
            
                <?php 
                    // Handle AJAX request (start)              
                    $codepostal = 0;
                    if( isset($_POST['codePostal']) ){
                        $codepostal = $_POST['codePostal'];
                    }
                    $comm_arr = array();
                    if($codepostal > 0){
                        
                        // Query Db and store the Countries corresponding to Zip Code in an aray
                        $req = "    SELECT communes.CommuneId cid,NomCommune FROM communes
                                    LEFT JOIN communeCP
                                    ON communeCP.CommuneId = communes.CommuneId
                                    LEFT JOIN codesPostaux
                                    ON codesPostaux.CodePostalId = communeCP.CodePostalId
                                    WHERE codesPostaux.CodePostal = '$codepostal' ORDER BY NomCommune";
                        $rep = mysqli_query($db,$req);
                        while ($row = mysqli_fetch_array($rep)) {
                            $commId = $row['cid'];
                            $commune = $row['NomCommune'];      
                            $comm_arr = array("id" => $commId,"name" => $commune);
                        }
                    }
                    
                    // encoding array to json format
                    echo json_encode($comm_arr);
                ?>
            <!-- Countries dropdown list -->
            <select name="commune" id="commune">
                <option value="0">Sélectionner une commune</option>
            </select>
        </form>
        
    </body>
</html>
,

因此,我资助了解决方案。现在,我正在尝试添加功能。我将基于单选按钮选择在下拉列表的旧区域或新区域中显示。 该功能有效。但是,我不知道如何显示部门。我需要2个区域变量,一个用于新区域,另一个用于选择旧区域。但是它们不会发送到PHP。这是我的代码:

    var gReg = {};
var reg = {};

$(document).ready(function(){
    $("input[name='choix']").click(function(){
        
        // Populate Dropdownlist with new region names
        if ($(this).val() === '1') {
            $('#region').find('option').not(':first').remove();
            
            // AJAX request
            $.ajax({
                url: 'communes.php',type: 'post',data: {request: 1},success: function(response){
                    $("#region").click(function(){
                        var len = response.length;
                        for( var i = 0; i<len; i++){
                            var grandeRegionId = response[i]['grandeRegionId'];
                            var nomGrandeRegion = response[i]['nomGrandeRegion'];
                            function gReg() {
                                regype.gdeRegId = grandeRegionId;
                            } 
                            $("#region").append("<option value='"+grandeRegionId+"'>"+nomGrandeRegion+"</option>");
                        }
                    });

                }
            });
        // Populate Dropdownlist with old region names
        } else if ($(this).val() === '2') {
        
        // AJAX request
            $.ajax({
                url: 'communes.php',data: {request: 2},success: function(response){
                    $("#region").click(function(){
                        var len = response.length;
                        for( var i = 0; i<len; i++){
                            var regionId = response[i]['regionId'];
                            var nomRegion = response[i]['nomRegion'];
                            function reg() {
                                regype.regId = regionId;
                            }
                            $("#region").append("<option value='"+regionId+"'>"+nomRegion+"</option>");
                        }
                    });
                }
            });
        }
        // End condition

        
        // Populate dropdown list with departments                                  
        $('#region').blur(function(){
            function regionType() {
                regype.gdeRegId = grandeRegionId;
                
                // AJAX request
                // Populate it with departments based on grandeRegionId (New Regions)
                if (grandeRegionId > 0) {
                    $.ajax({
                        url: 'communes.php',data: {request: 3,grandeRegionId: gdRegId},success: function(response){
                            $("#departement").click(function(){ 
                                var len = response.length;
                                for( var i = 0; i<len; i++){
                                    var departementId = response[i]['departementId'];
                                    var nomDepartement = response[i]['nomDepartement'];
                                    $("#departement").append("<option value='"+departementId+"'>"+nomDepartement+"</option>");
                                }
                            });
                        }
                    });
                    
                // Populate it with departments based on regionId (Old Regions)
                } else if (regionId > 0) {
                    var regId = $(this).val();
                    function regionType() {
                        regype.regId = regionId;
                        // AJAX request
                        if (regionId > 0) {
                            $.ajax({
                            url: 'communes.php',regionId: regId},success: function(response){
                                $("#departement").click(function(){ 
                                    var len = response.length;
                                    for( var i = 0; i<len; i++){
                                        var departementId = response[i]['departementId'];
                                        var nomDepartement = response[i]['nomDepartement'];
                                        $("#departement").append("<option value='"+departementId+"'>"+nomDepartement+"</option>");
                                    }
                                });
                            }
                        }
                    });
                }
            }
        });
    });
});