I've been too busy at work lately. In an AJAX request, the background returns a JSON string and a JSON array of scenes, as well as the foreground processing example.
Look directly at the code.
background responses to JSON strings
Package Com.ajax;import Java.io.ioexception;import Java.io.printwriter;import javax.servlet.ServletException; Import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.HttpServletResponse; @WebServlet ("/jsonstr") public class Jsonstr extends HttpServlet {/** * */private static final long serialversionuid = 1L; @Overrideprotected V OID Doget (httpservletrequest req, HttpServletResponse resp) throws Servletexception, IOException {//Construct JSON object string Resstr = "{" + "Name:" + "\" zhangsan\ "," + "ID:" + "\" id001\ "" + "}";//Output JSON object to foreground printwriter out = Resp.getwriter (); Write (RESSTR); Out.flush (); Out.close ();} @Overrideprotected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { Doget (req, resp);}}
background responses to JSON arrays
Package Com.ajax;import Java.io.ioexception;import Java.io.printwriter;import javax.servlet.ServletException; Import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.HttpServletResponse; @WebServlet ("/jsonarr") public class Jsonarr extends HttpServlet {/** * */private static final long serialversionuid = 1L; @Overrideprotected void Doget (httpservletrequest req, HttpServletResponse resp) throws Servletexception, IOException {//Construct JSON object string RESSTR1 = "{" + "Name:" + "\" zhangsan\ "," + "ID:" + "\" id001\ "" + "}"; String resStr2 = "{" + "Name:" + "\" Lisi\ "," + "ID:" + "\" id002\ "" + "}"; String resStr3 = "{" + "Name:" + "\" Wangwu\ "," + "ID:" + "\" id003\ "" + "}"//construct JSON array string jsonarr = "[" + ResStr1 + "," + RESSTR2 + "," + RESSTR3 + "]";//output JSON array to foreground printwriter out = Resp.getwriter (); Out.write (Jsonarr); Out.flush (); out.close ();} @Overrideprotected void DoPost (HttpServletRequest req, HttpservletrespoNSE resp) throws Servletexception, IOException {doget (req, resp);}}
Front Page
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
page
Effects after clicking the Jsonstr and Jsonarr buttons
Well, finishing up, the sample is for learning only.
Yes, there is a little doubt that the previous callback function, the time to get the response data is directly through the Data.responsetext to obtain, today's code must use Data.target.responseText, do not know why? Have a friend to know please tell me, thank you very much.
Ajax response JSON strings and JSON arrays