如何动态地将选项添加到使用从 php 脚本检索的 json 数据构建的选择列表?
我有一个 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数据被修改&发回服务器读取 &将其存储到数据库中。使用此更改的数据刷新/重新绘制列表。
I have an HTML form that builds a drop-down from json data that is retrieved dynamically on page load from a php script.
<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>
The php script fetches data from a MySQL table.
<?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);
?>
I need to add functionality to it now that new options can be added dynamically from the form to the list. How can I do it? I am thinking to do it like user adds an option to a text box & presses a button. The same JSON data is modified & posted back to server that reads & stores it into database. The list is refreshed/re-drawn with this changed data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)