json(在JSP中) 应用实例

JSP端:

 1 <head>
2 <script type="text/javascript" src="json.js"></script>
3 <script type="text/javascript">
4 var http_request = false;
5 function send_request(url)
6 {
7 http_request = false;
8 if(window.XMLHttpRequest) {
9    http_request = new XMLHttpRequest();
10    if (http_request.overrideMimeType)
11 {
12    http_request.overrideMimeType('text/xml');
13   }
14 }else if (window.ActiveXObject)
15 {
16    try {
17     http_request = new ActiveXObject("Msxml2.XMLHTTP");
18    }
19 catch (e)
20 {
21     try
22 {
23     http_request = new ActiveXObject("Microsoft.XMLHTTP");
24     }
25 catch (e) {}
26    }
27 }
28 if (!http_request)
29 {
30   window.alert("不能创建XMLHttpRequest对象实例.");
31    return false;
32 }
33 http_request.onreadystatechange = processRequest;
34 http_request.open("GET", url, true);
35 http_request.send(null);
36 }
37  function processRequest()//返回结果处理函数
38 {
39    if (http_request.readyState == 4)
40 {
41    if (http_request.status == 200) {
42 var f=JSON.parse(http_request.responseText);
43 //f中存有json格式的数据。通过f.attribute就可以访问json
44 中的内容了
45 } else
46 {
47   alert("您的网络有异常");
48     }
49    }
50   }
51 function getFunction(){
52 send_request('/***.do?');
53 }
54 </head>

服务端:

 1 import org.json.JSONException;
2 import org.json.JSONObject;
3 public class GetFunctionAction extends Action {
4 public ActionForward execute(ActionMapping mapping, ActionForm form,
5 HttpServletRequest request, HttpServletResponse response) {
6 JSONObject jsonObj=new JSONObject();
7 try {
8 jsonObj.put("name", "**");
9 //……
10 } catch (JSONException e) {
11 e.printStackTrace();
12 }
13 response.setContentType("text/html");
14 response.setCharacterEncoding("gb2312");
15 try {
16 PrintWriter out=response.getWriter();
17 out.println(jsonObj.toString());
18 out.flush();
19 out.close();
20 } catch (IOException e) {
21 e.printStackTrace();
22 }
23 return null;
24 }
25 }



 
原文地址:https://www.cnblogs.com/windlaughing/p/2415610.html