<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/jquery.js"></script> <script> $(function(){ $('#btnok').bind('click',function(){ var data = { '_':new Date().getTime() }; //发送ajax请求 $.get('ajax7.php',data,function(msg){ //第一种方案 /* for(var i=0; i<msg.length;i++){ var id = msg[i].id; var username = msg[i].username; var op = new Option(username,id); $('#category')[0].options.add(op); } */ //第二种方案 $(msg).each(function(i,item){ var id = item.id; var username = item.username; var op = new Option(username,id); $('#category')[0].options.add(op); }); },'json'); }); }); </script> </head> <body> <input type="button" id="btnok" value="获取数据" /> <hr /> <select id="category"></select> </body> </html>
php代码如下:
<?php mysql_connect('localhost','root',''); mysql_query('use xsphp'); mysql_query('set names utf8'); //组装SQL语句 $sql = 'select * from admin'; $res = mysql_query($sql); $data = array(); while($row = mysql_fetch_assoc($res)){ $data[] = $row; } //生成json数据 echo json_encode($data);