dongmeiran609914 2015-01-04 12:22
浏览 480

我如何在下拉菜单中从数据库中获取数据

I tried the following but id didn't work

//PHP CODE

$query = "SELECT kategorite FROM kategorite";

$data = mysql_query($conn, $query);

$makes = array();

while($row = mysql_fetch_array($data))
{
array_push($makes, $row["Lloji"]);
}
echo json_encode($makes);

//JAVASCRIPT CODE

$(document).ready(function () {

$.getJSON("getTipin.php", success = function(data)
{
var options = "";

for(var i=0; i < data.length; i++)

{

 options += "<option value='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";

}

$("#type").append(options);

$("type").change();
});
  • 写回答

1条回答 默认 最新

  • dongling4383 2015-01-04 13:53
    关注

    The code contains some little errors, in addition to those addressed in the other comments. For example you call change() on $('type') instead of $('#type'). Also, not all browsers take well not being supplied with JSON's content type.

    In general this problem is made up of two parts:

    Fetch the data and output JSON

    // Here I strongly suggest to use PDO.
    
    $dbh = new PDO('mysql:host=localhost;port=3306;dbname=database', 'user', 'password',
        array(
            PDO::ATTR_PERSISTENT        => true,
            PDO::ATTR_EMULATE_PREPARES  => false,
            PDO::ATTR_ERRMODE           => PDO::ERRMODE_EXCEPTION
        )
    );
    $query  = "SELECT kat_id, kategorite FROM kategorite WHERE kategorite LIKE :search";
    $stmt   = $dbh->prepare($query);
    
    // Always check parameter existence and either issue an error or supply a default
    $search = array_key_exists('search', $_POST) ? $_POST['search'] : '%';
    
    $stmt->bindParam(':search', $search, PDO::PARAM_STRING);
    $stmt->execute();
    $reply = array();
    while ($tuple = $stmt->fetch(PDO::FETCH_NUM)) {
        $reply[] = array(
            'value' => $tuple['kat_id'],
            'text' => $tuple['kategorite'],
        );
    };
    
    // See: http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type
    Header('Content-Type: application/json');
    
    // Adding Content-Length can improve performances in some contexts, but it is
    // needless with any kind of output compression scheme, and if things go as they
    // should, here we have either zlib or gz_handler running.
    
    // die() ensures no other content is sent after JSON, or jQuery might choke.
    die(json_encode($reply));
    

    Populate combo box from JSON in jQuery

    function fillCombo($combo) {
        $.post('/url/to/php/endpoint',
            { search: '%' },
            function(options) {
                for (i in options) {
                    $combo[0].options[i] = {
                        value: options[i].value,
                        text : options[i].text
                    };
                }
                $combo.change();
            }
        );
    }
    
    fillCombo($('#comboBox');
    

    In this case since the data returned is in the same format used by the comboBox, you could also shorten and accelerate things with:

            function(options) {
                $combo[0].options = options;
                $combo.change();
            }
    

    In general you want the server to do as little work as possible (server load costs money and impacts performances), but also the client to do as little work as possible (client load impacts site's perception and responsivity). What data exchange format to use is something almost always worth thinking upon.

    For very long lists without paging, for example, you might want to cut the data being sent, by only encoding the option's text. You will then send

    [ 'make1','make2','make3'... ]
    

    instead of

    [ { "option": "1", "value": "make1" }, { "option": "2", "value": "make2" }, ... ]
    

    and use a slower client cycle to fill up the combo box.

    评论

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端