dongsao8279 2012-06-03 13:17
浏览 56
已采纳

使用jQuery填充数据库中的选择框

I am trying to populate a select box from values from a mysql database, using jQuery.

db call:

<?php 
include 'db.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);

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

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

HTML:

<select id="a1_title">
  <option>Default</option>
</select>

There are a bunch of examples that I have found, but nothing specifically related to what I am looking for, unless the force is not with me today.

Is there a link someone can point me to?

  • 写回答

3条回答 默认 最新

  • douzi2749 2012-06-03 13:25
    关注

    The below script will load the dropdown list from the JSON received from the PHP Page.

    $(function(){
    
      var items="";
      $.getJSON("yourPHPPage.php",function(data){
    
        $.each(data,function(index,item) 
        {
          items+="<option value='"+item.ID+"'>"+item.Name+"</option>";
        });
        $("#a1_title").html(items); 
      });
    
    });
    

    Assuming the received JSON is in this format

    [ { "ID" :"1", "Name":"Scott"},{ "ID":"2", "Name":"Jon"} ]
    

    Another thing i noticed is that you are doing SELECT * FROM table name to get the items. I do not think you should do that. You should do only two columns (ID & NAME , if you you have those columns in your table.).

    Here is a JSFiddle example to show how to fetch data from the JSON.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形