首页 文章

填充下拉菜单(选择)

提问于
浏览
0

我一直试图根据这个答案解决我的问题:Populate select box from database using jQuery

我试图实现那里的答案,但我在这里没有运气 . 截至目前,下拉菜单中显示的是默认的“Stone”项目 .

任何人都可以节省一些时间,并帮我解决问题 . 我的代码本质上应该从MySQL数据库中读取,该数据库具有超过150个ID,从1开始,并在相同ID的行中使用相应的名称来填充加载时的下拉菜单 .

下拉菜单的内容示例如下:

  • 石头

  • 钻石

相应的DB会是什么样子:

ID           item_name
1            Stone
2            Grass
3            Diamond

我用来尝试这样做的代码是:

PHP (process_item_list.php):

$con = mysql_connect($DB_HOST,$DB_USER,$DB_PASSWORD);
$dbs = mysql_select_db($DB_NAME, $con);

$tableName = "itemlist";
$result = mysql_query("SELECT * FROM $tableName");

$data = array();
while ( $row = mysql_fetch_row($result) )
{
    $data[] = $row;
}
echo json_encode( $data );    
?>

jQuery/Javascript

<script type="text/javascript">
$(function(){
      var items="";
      $.getJSON("process_item_lists.php",function(data){
        $.each(data,function(index,item) 
        {
          items+="<option value='"+item.id+"'>"+item.name+"</option>";
        });
        $("#tradeItems").html(items); 
      });
    });
</script>

HTML

<select id="tradeItems"> 
<option value="">Stone</option>
</select>

我也愿意采用不同的方式来做到这一点,只要它在加载时仍然填充下拉菜单!

Edit: With the help of wirey the PHP issue is fixed. Here is what the results look like from running the PHP file: http://fogest.net16.net/mctrade/php/process_item_list.php When I run the actual page using the alert boxes which should give me the ID and the item name they both return undefined rather then the correct values.

1 回答

  • 1

    http://fogest.net16.net/mctrade/php/process_item_list.php的结果没有预料到,它看起来像这样:

    [ ["1","Stone","images\/stone.png"],
      ["2","Grass Block","images\/grass_block.png"],
      /* snip a lot of rows */
    ]
    

    但你期待的是这样的:

    [ { "id":"1", "name":"Stone", "image?":"images\/stone.png"},
      { "id":"2", "name":"Grass Block","image?":"images\/grass_block.png"},
      /* and so on */
    ]
    

    我认为你会想要使用mysql_fetch_assoc()而不是mysql_fetch_row(),这可能会给你正确的输出 .

    Bonus: 您可以通过在 echo 之前添加一行来为响应提供正确的内容类型:

    header("Content-type: application/json");
    echo json_encode($data);
    

    Remark: 当我检查了http://fogest.net16.net/mctrade/php/process_item_list.php的来源时,我在最后发现了这个:

    <!-- Hosting24 Analytics Code -->
    <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
    <!-- End Of Analytics Code -->
    

    这不应该是响应的一部分,它可能会使JSON解析器崩溃 .

相关问题