Ajax responds to json strings and json Arrays
Recently I was too busy at work. I took the time to sort out ajax requests at night. The background returned json strings and arrays, as well as the front-end processing examples.
View the Code directly.
Json string background response
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 void doGet (HttpServletRequest req, httpServletResponse resp) throws ServletException, IOException {// construct the json object String resStr = "{" + "name:" + "\" zhangsan \ "," + "id: "+" \ "id001 \" "+"} "; // output the json object to the foreground PrintWriter out = resp. getWriter (); out. write (resStr); out. flush (); out. close () ;}@ Overrideprotected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet (req, resp );}}
Json array background response
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 the json object String resStr1 = "{" + "name:" + "\" zhangsan \ "," + "id: "+" \ "id001 \" "+"} "; String resStr2 =" {"+" name: "+" \ "lisi \", "+" id: "+" \ "id002 \" "+"} "; String resStr3 =" {"+" name: "+" \ "wangwu \", "+" id: "+" \ "id003 \" "+"} "; // construct a json array String jsonArr =" ["+ resStr1 +", "+ resStr2 + ", "+ resStr3 +"] "; // output the json array to the 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-end page
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Page
Effect after clicking the JsonStr and JsonArr buttons
All right. The samples are only for learning.
By the way, there is a bit of doubt. In the previous callback function, when obtaining response data, it was obtained directly through data. responseText. Today's Code uses data.tar get. responseText. Why? If you know something, please let me know. Thank you very much.