我有一个带有单选按钮的表单,单击时我将其传递给一个servlet,该servlet从mysql表中获取数据并将其显示在带有复选框的同一页面中。
<input type="radio" name="id" value="1">
<input type="radio" name="id" value="2">
<script>
$(document).ready(function(){
$('input[name=id]').change(function (){
var var_name = $(this).val();
console.log(var_name);
$.getJSON("ServletCode", "id="+var_name,function(data){
var myValues = data.toHtml;
$("#guts").html(myValues);
});
});
});
</script>
我的servlet代码是:
JSONObject jsonObj = new JSONObject();
List<String> myList = new ArrayList<String>();
username = rs.getString("name");
id = rs.getString("userid");
myList.add(username);
myList.add(userid);
jsonObj.put("toHtml", myList.toArray());
response.setContentType("application/json");
response.getWriter().write(jsonObj.toString());
我想使用这些值“id”和“name”以及一个复选框创建一个表。当单击复选框时,我需要再次显示从 mysql 获取的他的“标记”。
最佳答案
如果我理解正确的话,你的 JSON 将是
{"toHtml":["someNameValue", "someUserId"]}
但是,如果您要拥有多个用户名-ID 对,它们可能需要自己的 JSON 对象。迭代它们会更容易
您需要做的是使用 javascript 创建一个表
var table = "<table>";
table += "<thead><tr><th>username</th><th>id</th></tr></thead>";
table += "<tbody>";
// loop through the array elements and create rows
table += "</tr><td>" + /* get the username from the json */ + "</td>";
table += "<td>" + /* get the userid from the json */ + "</td>";
// add a javascript callback to a checkbox to display the grades in a similar way
// done loop
table += "</tbody>";
然后您可以将此表附加到其他一些 html 元素并使其可见。
关于java - 使用 json 从单选按钮输入显示动态 mysql 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615622/