使用jQuery从数据库填充选择框

问题描述:

我正在尝试使用jQuery从mysql数据库中的值填充选择框.

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

数据库调用:

<?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?

以下脚本将从PHP页面接收的JSON加载下拉列表.

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); 
  });

});

假设接收到的JSON采用这种格式

Assuming the received JSON is in this format

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

我注意到的另一件事是,您正在执行SELECT * FROM表名来获取项目.我不认为你应该这样做.您应该只做两列(如果您的表中有这些列,则为ID& NAME.).

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.).

这是一个 JSFiddle示例,展示了如何从JSON获取数据.

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