English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example of ajax response json string and json array (detailed explanation)

I've been too busy at work recently, so I will take some time tonight to organize the scenarios of backend returning JSON strings and JSON arrays in AJAX requests, as well as the example of front-end processing.

Directly look at the code.

Backend response in JSON string format

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;
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException {
 // construct json object
 String resStr = "{" + "name:" + "\"zhangsan\"," + "id:" + "\"id001\" + "]";
 // Output JSON object to the front-end
 PrintWriter out = resp.getWriter();
 out.write(resStr);
 out.flush();
 out.close();
 }
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException {
 doGet(req, resp);
 }
}


back-end response of json array

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;
 @Override
 protected 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 the front-end
 PrintWriter out = resp.getWriter();
 out.write(jsonArr);
 out.flush();
 out.close();
 }
 @Override
 protected 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"%>"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Json</title>
</head>
<body>
 <br><br>
 <input type="button" value="JsonStr" onclick="jsonStr()" />
 <br><br>
 <table>
 <tr>
  <td>username</td>
  <td><input id="username"></td>
 </tr>
 <tr>
  <td>id</td>
  <td><input id="id"></td>
 </tr>
 </table>
 <br><br><br>
 <input type="button" value="JsonArr" onclick="jsonArr()" />
 <br><br>
 <table border="1" bordercolor="red">
 <caption>Json Array</caption>
 <thead>
  <tr>
  <th>Username</th>
  <th>Id</th>
  </tr>
 </thead>
 <tbody id="tb">
 </tbody>
 </table>
</body>
<script type="text/javascript">
 // json string processing method
 function jsonStr() {
 var xhr = new XMLHttpRequest();
 xhr.open("get", "jsonStr");
 xhr.onreadystatechange = function(data) {
  if (xhr.readyState == 4 && xhr.status == 200) {
  // Convert json string to json object
  var obj = eval("(" + data.target.responseText + )")
  document.getElementById("username").value = obj.name;
  document.getElementById("id").value = obj.id;
  }
 };
 xhr.send(null);
 }
 // json array processing method
 function jsonArr() {
 var xhr = new XMLHttpRequest();
 xhr.open("get", "jsonArr");
 xhr.onreadystatechange = function(data) {
  if (xhr.readyState == 4 && xhr.status == 200) {
  // Convert the JSON string to a JSON array
  var obj = eval("(" + data.target.responseText + )")
  // Create a code fragment to store table rows
  var oFragment = document.createDocumentFragment();
  // Generate row data according to the length of the JSON array
  for (var i=0; i<obj.length; i++) {
   var trObj = document.createElement("tr");
   trObj.innerHTML = "<td>" + obj[i].name + "</td><td>" + obj[i].id + "</td>";
   oFragment.appendChild(trObj);
  }
  // Add the row data to the tBody part of the table
  document.getElementById("tb").appendChild(oFragment);
  }
 };
 xhr.send(null);
 }
</script>
</html>

Page illustration

Effect after clicking the JsonStr and JsonArr buttons

Alright, the organization is complete, and the example is for learning purposes.

By the way, there is a little doubt. In the previous callback function, when getting the response data, it was always directly obtained through data.responseText. Why must we use data.target.responseText in today's code? Does anyone know? Please inform friends who know, thank you very much.

This instance of the AJAX response JSON string and JSON array (detailed explanation) is all the content that the editor shares with everyone. I hope it can be a reference for everyone, and I also hope everyone will support the呐喊 tutorial more.

You may also like