根据文本输入字段填充省份的下拉菜单

时间:2013-01-23 18:08:50

标签: php jquery mysql ajax jquery-ui

我有一个简单的用户表,显示用户信息,例如他们当前的国家和省份。

<td><b>Country</b></td>
        <td width="331">
        <form method="post" action="">
        <div id="countryList" style="vertical-align:top; display:inline-block; float:left;"><?=$country?></div>
        <input type="submit" name="submitCountry" id="submitCountry" class="ui-icon ui-icon-disk" style="border:none; display:none; background-color:transparent; float:right; vertical-align:top;" />  
        </td>
        <td width="336">&nbsp;</td>
      </tr>
      <tr>
        <td><b>Province</b></td>
        <td>
        <div id="provinceList" style="vertical-align:top; display:inline-block; float:left;"><?=$province?></div>
        </form>
      </td>

当用户点击他们的国家/地区时,DIV会转换为具有自动完成功能的输入框,并向数据库发起AJAX请求。这允许用户键入一个国家,它将显示在列表中。

jQuery代码:

$("#countryList").click(function(){

            $("#submitCountry").css("display", "inline");

            //check if there are any existing input elements
            if ($(this).children("input").length == 0){


                //variable that contains input HTML to replace
                var inputbox = "<input type='text' id='countryList' class='inputbox' name='country' value=\""+$(this).text()+"\">";    
                //insert the HTML intp the div
                $(this).html(inputbox);         

                //automatically give focus to the input box     
                $(".inputbox").focus();

                //maintain the input when it changes back to a div
                $(".inputbox").blur(function(){
                    $("#submitCountry").css("display", "none");

                    var value = $(this).val();
                    $("#country").val(value);
                    $("#countryList").text(value);

                });
            }  


            //Once input box is displayed assign it the autocomplete method
            $("input#countryList").autocomplete ({
                //set a few options, and select source data
                minLength : 2,
                source : function (request, callback)
                {
                    //variable that will carry the request 'term' from url
                    var data = { term : request.term };

                    //ajax method to call pho script
                    $.ajax ({
                        url : "getCountry.php",
                        data : data,
                        complete : function (xhr, result)
                        {
                            //if returns empty, then exit out
                            if (result != "success") return;

                            //otherwise get response and fill country array
                            var response = xhr.responseText;
                            var country = [];
                            //filter each li item
                            $(response).filter ("li").each (function ()
                            {
                            //display li item inline
                            country.push ($(this).text ());
                            });
                            //display country list
                            callback (country);
                        }

                    });
                }

            });   
if ($("#provinceList").children("input").length == 0){

                var selectbox = "<select id='selectProv' name='selectProv'></select> ";

                $("#provinceList").html(selectbox);

                var datastring = { term : request.term };
                $.ajax({
                    url: "getProvince.php",
                    data: datastring, 
                    success: function(html){
                        $(".selectProv").html(html);
                    }
                })
            }

getCountry.php文件如下。是的,我知道,我需要保护自己免受SQL注入。目前我还没有走得那么远(我是学生)。

这是getCountry.php

 <?php

$term = $_REQUEST["term"];
$term = utf8_decode ($term);
$dbUser = "admin";
$dbPass = "pass";
$dbName = "testdb";
$bd = mysql_connect ("localhost", $dbUser, $dbPass);
$ret = mysql_select_db ($dbName, $bd);
$query = sprintf ("SELECT * FROM Country WHERE Name LIKE '%%" . $term . "%%'", mysql_real_escape_string($term));

//send query string to DB
$result = mysql_query($query);

//if result returns a value
if ($result != NULL){

    // Use the result (sent to the browser)
    while ($row = mysql_fetch_assoc($result)){

        echo ("<li>" . utf8_encode ($row["Name"]) . " (" . utf8_encode ($row["Code"]) . ")</li>");

    }

    mysql_free_result($result);
}

mysql_close ($bd);

?>

getProvince.php 此代码将用于查询数据库并生成下拉菜单。我知道这段代码有效,因为我可以导航到它,并传递一个字符串,它将生成我需要的下拉列表。问题是它在整个应用程序中不起作用。

    <?php

$term = $_REQUEST["term"];
$term = utf8_decode ($term);
$dbUser = "admin";
$dbPass = "pass";
$dbName = "testdb";
$bd = mysql_connect ("localhost", $dbUser, $dbPass);
$ret = mysql_select_db ($dbName, $bd);
$query = sprintf ("SELECT * FROM Country WHERE Name LIKE '%%" . $term . "%%'", mysql_real_escape_string($term));

//send query string to DB
$result = mysql_query($query);

//if result returns a value
if ($result != NULL){

    $row = mysql_fetch_assoc($result);
    $code = $row['Code'];

    $sql = "SELECT DISTINCT District FROM City WHERE CountryCode='$code'";

    $result = mysql_query($sql);

    ?>
    <option>Select State/Province</option>
    <?php while($row=mysql_fetch_array($result)){

        echo "<option value=" . $row['District'] . ">" . $row['District'] . "</option>";
    }

    mysql_free_result($result);
}

mysql_close ($bd);

以上代码在某种程度上起作用。我能够获得国家/地区文本框以正确查询数据库并执行自动完成方法,但结果不会填充省份的下拉列表,就像我也想要它们一样!提前谢谢

1 个答案:

答案 0 :(得分:1)

您的查询未被清理!!!!!!!!!!!!!!!!! ,两者都没有正确连接,您可以更简单地执行:

$query = "SELECT * FROM Country WHERE Name LIKE '%" . mysql_real_escape_string($term) . "%'";

请始终清理您的输入,这比使用工作脚本更重要,因为您冒着数据库完整性的风险

此行应该清理,无关紧要连接的数据来自数据库

$sql = "SELECT DISTINCT District FROM City WHERE CountryCode='" . mysql_real_escape_string($code) . "'";

以下行应为:

$.ajax({
                url: "getProvince.php",
                data: datastring, 
                success: function(html){
                    $("#selectProv").html(html);
                }
            });

注意 .selectProv 更改为 #selectProv 表示'id',。表示'class')

相关问题