[英]How to dynamically add an option to a select list that is build using json data retrieved from a php script?
我有一个HTML表单,该表单从json数据构建一个下拉列表,该列表是从php脚本在页面加载时动态检索到的。
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});});
});
</script></head>
<body>
<form name="index">
<select name="user_spec" id="user_spec" />
</form>
</body>
</html>
php脚本从MySQL表中获取数据。
<?php
$username = "user";
$password = "********";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test"); $query =
"SELECT * FROM user_spec";
$result=mysql_query($query);
$outArray = array();
if ($result) {
while ($row = mysql_fetch_assoc($result)) $outArray[] = $row;
}
echo json_encode($outArray);
?>
现在,可以将新选项从表单动态添加到列表,因此我需要为其添加功能。 我该怎么做? 我在想这样做,就像用户在文本框中添加选项并按下按钮一样。 相同的JSON数据将被修改并发布回服务器,该服务器将其读取并存储到数据库中。 使用此更改的数据刷新/重新绘制列表。
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$("#user_spec").html("");//clear old options
jsonData= eval(jsonData);//get json array
for (i = 0; i < jsonData.length; i++)//iterate over all options
{
for ( key in jsonData[i] )//get key => value
{
$("#user_spec").get(0).add(new Option(jsonData[i][key],[key]), document.all ? i : null);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.