ajax/json
程序员文章站
2024-02-26 13:36:40
...
JSP页面:
JS:
JAVA代码:
<select id="province" name="user.province" onchange="duplicateAddress()">
<s:iterator value="provinceList" var="item">
<option value="<s:property value='key'/>">
<s:property value="value"/></option>
</s:iterator>
</select>
<select id="city" name="user.city">
<s:iterator value="cityList" id="citys">
<option value="<s:property value='key'/>">
<s:property value="value"/></option>
</s:iterator>
</select>
JS:
function duplicateAddress() {
var alterCity = $("#province").attr("value");
$.ajax({
async : false,
type: "POST",
url: "./alterAddress.action",
data: "alterCity=" + alterCity,
success: function(result){
if (result != null) {
var cityInfo = eval('('+result+')');
var citySelect = $("#city");
citySelect.children("option").remove();
$("<option value='0'>不限</option>").appendTo(citySelect);
for(var i=0;i<cityInfo.length;i++){
$("<option value='"+cityInfo[i].value+"'>"+cityInfo[i].text+"</option>").appendTo(citySelect);
}
}
}
});
}
JAVA代码:
public String alterAddress(){
StringBuffer result = new StringBuffer();
StringBuffer buffer = new StringBuffer();
result.append("[");
//从xml中取得省、市放入map中传到前台
List<Map<String, Object>> list = CityUtil.getCityList();
//根据省找到对应市集合
for (Map<String, Object> map : list) {
//如果取得的省与前台选择的省相同
if(((String) map.get("value")).equals(alterCity)){
List<Map<String, String>> childList = (List<Map<String, String>>) map.get("children");
for (Map<String, String> child : childList) {
buffer.append("{")
.append("value")
.append(":")
.append("'"+(String) child.get("value")+"'")
.append(",")
.append("text")
.append(":")
.append("'"+(String) child.get("name")+"'")
.append("}")
.append(",");
}
if (buffer.length() != 0) {
result.append(buffer.substring(0, buffer.length() - 1));
}
result.append("]");
try {
this.sendAjaxResponse(result.toString());
} catch (Exception e) {
e.printStackTrace();
log.debug(e.getMessage());
}
}
}
return null;
}
上一篇: MVC与MVVM的理解