简体   繁体   English

使用 jQuery 从数据库填充下拉列表

[英]Populate dropdown list from database using jQuery

I want to populate the dropdown list from database using jQuery.我想使用 jQuery 从数据库中填充下拉列表。 But when i tried, i am getting empty response.但是当我尝试时,我得到了空洞的回应。 see below code I didn't see any error.看下面的代码我没有看到任何错误。

PHP code to get data:获取数据的PHP代码:

if ($dat=="driver") {
    $q = "select * from drivers";
    $sql = mysql_query($q);
    $data = array();
    while($row = mysql_fetch_array($sql, true)){
        $data[] = $row; 
    };
    echo json_encode($data);
}

jQuery code: jQuery代码:

$.getJSON("get-data.php?dat=driver",function(data){
    $.each(data,function(key,val) {
        $("#night_Shift_text").append(
            $("<option></option>").val(value.id).html(value.id)
        );     
    });
});

HTML: HTML:

<select id='night_Shift_text'><option></option></select>

Debug console:调试控制台:

在此处输入图片说明

Use a string to store your option, and then append it to the select tag.使用字符串存储您的选项,然后将其附加到 select 标签。 Then, please check that data is there in the val.然后,请检查 val 中是否有数据。

$.getJSON("get-data.php?dat=driver",function(data){
    var stringToAppend = "";
    $.each(data,function(key,val) {

       stringToAppend += "<option value='" + val.id + "'>" + val.id + "</option>";

    });

    $("#night_Shift_text").html(stringToAppend);
});

You are using wrong variable value .您使用了错误的变量value You need to use val您需要使用val

        $("<option></option>").val(val.id).html(val.id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM