我有一个 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);
}
}
});
关于php - 如何动态地将选项添加到使用从 php 脚本检索的 json 数据构建的选择列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4014667/