很早就想研究一下ajax 通过json 方式走action 返回list 给前台 显示,今天终于做出来了,把代码贴出来分享给大家ajax json 方式需要jar包,一会从附件分享给大家。
首先我用的开发框架式ssi2,接下来我把代码帖给大家。
(1)前台页面jhxdxukezheng.jsp
function plannochange(){
var planno=$("#planno").val();
$.ajax({
type : 'post',
url : 'SampleAction_selectProducttypeByPlanno',
dataType:'json',
data : {
planno : planno,
},
success : function(data) {
// alert(data);
$("#producttype").empty();
// $("#producttype").append("请选择");
$.each(data, function (i, item) {
// alert(item.name + "," +item.value);
$("#producttype").append(""+item.value+"");
});
},
error:function(){
alert("错误");
}
});
};
计划编号:
listValue="planno" id="planno" οnchange="plannochange()">
产品类型:
(2)action 类
public String selectProducttypeByPlanno() {
response.setContentType("text/html;charset=UTF-8");
String planno = request.getParameter("planno");
List producttypelist = sampleService
.selectProducttypeByPlanno(planno);
JSONArray jsonarry = JSONArray.fromObject(producttypelist);
try {
PrintWriter out = response.getWriter();
System.out.println(jsonarry.toString());
out.print(jsonarry.toString());
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
注:1.这里数据传输方式为:json方式{"1":"aa","2":"bb"}
2. $("#producttype").empty()代表下拉列表清空 alert(item.name + "," +item.value);
$("#producttype").append(""+item.value+"");代表下来列表追加
3.JSONArray jsonarry = JSONArray.fromObject(producttypelist)代表把list集合转化成jsona rry格式,再 用PrintWriter流输出参数jsonarry.toString()返给前台页面