我正好在学习struts内容,所以以struts为例
1.首先在你的web项目里面导入如下文件
commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.3.jar
json-lib-2.1-jdk15.jar
2.写一个login.jsp示例,这里我只写 body体内容
<body>
<script type="text/javascript">
$(function(){
$("#s1").click(function(){
/*getJSON后面的三个参数分别 是 url,{key:value,key1:value1},callback回调函数,json是后台通过通过response得到的Printwriter写过来的*/
$.getJSON("<%=basePath%>/authority/test",{name:1}, function(json){
$("#s1").empty();
for(var v in json){
$("#s1").append("<option>"+json[v]+"<option>");
}
});
});
<!--click结束-->
})
</script>
<!--
这里举了各种json数据的处理可以供参考;
$(function(){
var json = {"name":"jack","gender":"male","height":174.00,"birthday":new Date()};//定义一个JSON对象
$("#b100").click(function(){
alert(json.birthday);
});
$("#b101").click(function(){
for(var key in json){
alert(json[key]);
}
});
var jsonarray = [{"节目名":"非诚勿扰","主播":"孟非","收视率":0.2},
{"节目名":"极限挑战","主播":"柳言","收视率":0.1},
{"节目名":"NBA","主播":"周建龙","收视率":0.3},
{"节目名":"妈妈米亚","主播":"妈妈","收视率":0.9},
{"节目名":"花样姐姐","主播":"林志灵","收视率":0.1},
{"节目名":"天天向上","主播":"汪涵","收视率":0.15}
];
$("#b102").click(function(){
/*
for(var index=0;index<jsonarray.length;index++)
alert( jsonarray[index]["节目名"]);
*/
for(var index in jsonarray){
var v="";
for(var key in jsonarray[index]){
v=key+"="+jsonarray[index][key]+"\t"+v;
}
alert(v);
}
});
$("#b103").click(function(){
var jsonstr =‘({"name":"rose","address":"江苏无锡"})‘;
var jsons = eval(jsonstr);
alert(jsons["name"]);
});
})
-->
<select id="s1">
</select>
</body>
3.struts自己配置(如果你是servlet。web.xml也自己配置),连接的一个action,代码如下:
public class TestJson extends ActionSupport {
/* (non-Javadoc)
* @see com.opensymphony.xwork2.ActionSupport#execute()
*/
@Override
public String execute() throws Exception {
//如果你的类是servlet,response可以直接用
HttpServletResponse response=ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
//2.数据以map为例
Map<String,String> map = new HashMap<String, String>();
map.put("100", "洗衣机");
map.put("101", "洗衣粉");
map.put("102", "电冰箱");
map.put("103", "空调");
map.put("104", "彩电");
map.put("105", "烤箱");
//3.将数据转化位json,在转化为字符串jsonstr;
String jsonstr = JSONObject.fromObject(map).toString();
//4.数据写出去
PrintWriter out = response.getWriter();
out.write(jsonstr);
out.flush();
out.close();
return super.execute();
}
}