【问题标题】:populating child combo box in javascript after getting data in JSON array objects在 JSON 数组对象中获取数据后在 javascript 中填充子组合框
【发布时间】:2012-02-11 14:03:23
【问题描述】:

我试过了,用谷歌搜索了很多,但仍在寻找解决方案。我的问题很简单,只是我想在父组合框中的 onchange 事件之后填充 index.jsp 中的子组合框。我已经使用 JSON 数组对象来检索但没有填充子组合,请问有什么帮助吗? 当我选择ABC 时,001 将自动填充到第二个组合框中,同样,当我选择PQR 时,002 将被填充,001 将被删除。

index.jsp

 <script type="text/javascript">
 $(document).ready(function() {
 $("#combobox1").change(function() {// by onchange event in parent combo box i want to populate 
 child combobox 
$.getJSON('state.jsp', {count : this.value}, function(responseData) {
$("#combobox2").append(
$("<option></option>").html(responseData.name).val(responseData.name)
);
});
});
});          
</script>

 <body>  
//parent combo box
<select id="combobox1" name="count">
<option value="abc">ABC</option>
<option value="pqr">PQR</option>
</select>
 // child combo box

<select id="combobox2" name="combobox2">// here i want to populate data `001` by `ABC` or `002` by selecting `PQR` , how can i do it?
<option value="">select</option>
</body> 

state.jsp

 <%@page import="net.sf.json.JSONObject"%>
 <%@page import="net.sf.json.JSONArray"%>
 <%
 String count=request.getParameter("count");
 if(count.equals("ABC"){
 JSONObject arrayObj= new JSONObject();
   arrayObj.put("name","001");// how to populate `001` in an option in child combo box when `ABC` will be selected in parent combo?
  response.setContentType("application/json");
  response.getWriter().write(arrayObj.toString());
}
else if (count.equals("PQR"){
 JSONObject arrayObj= new JSONObject();
arrayObj.put("name","002");// how to populate `002` in an option in child combo box when `PQR` will be selected in parent combo?
  response.setContentType("application/json");
  response.getWriter().write(arrayObj.toString());
}
%>

【问题讨论】:

  • 您没有使用 jquery,那么为什么要这样标记呢?顺便说一句,使用 jQuery 会让你的生活更轻松。
  • 我已经通过查看示例来尝试使用 jquery,但它不会在父组合中的 onchange 后立即触发,我必须从该下拉菜单中进行选择
  • 你能发布你的 jQuery 例子吗?
  • 我已经编辑了我的问题,请查看并提出任何想法
  • 这是作业吗,因为这是我今天看到的第二个,几乎相同的用法。

标签: javascript ajax json combobox


【解决方案1】:

使用我在Clean old options from child dropdown when receiving data by JSON中提供的示例代码

当您传回以下值之一时,您需要对count 字段进行不区分大小写比较(就像另一个线程中的原始海报所做的那样):

  • abc
  • pqr

你正在检查:

  • ABC
  • PQR

您要查找的内容永远不存在,因此您永远不会为第二个组合返回任何数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-26
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2018-11-14
    • 1970-01-01
    相关资源
    最近更新 更多