Handling JSON Data in AJAX Responses
When a server returns simple data, plain text is sufficient and easy to handle. Both frontend and backend implementations remain straightforward.
Frontend HTML/JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX Response Formats</title>
<script>
let httpRequest;
function fetchData() {
httpRequest = new XMLHttpRequest();
httpRequest.open('GET', 'textDataHandler', true);
httpRequest.onreadystatechange = displayData;
httpRequest.send();
}
function displayData() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
let responseText = httpRequest.responseText;
console.log(responseText);
}
}
</script>
</head>
<body>
<button type="button" onclick="fetchData()">Get Data</button>
</body>
</html>
Backend Servlet (Java):
@WebServlet("/textDataHandler")
public class TextDataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().print("Simple text response");
}
}
Processing complex data like objects or collections as plain text becomes cumbersome. JSON (JavaScript Object Notation) is a lightweight data interchange format ideal for this purpose. It is language-independent, human-readable, and easily parsed by machines, making network transmission efficient.
Key Advantages:
- Lightweight, designed for data serialization.
- Copmatible with both frontend JavaScript objects and backend data structures.
- Can be directly parsed into JavaScript objects.
- The default data format for many AJAX libraries, including jQuery.
JSON Syntax and Usage in JavaScript:
// Creating a JSON object
let employee = {"firstName": "John", "employeeId": 101};
alert(employee.firstName); // John
alert(employee.employeeId); // 101
// Creating an array of JSON objects
let team = [
{"firstName": "Alice", "employeeId": 102},
{"firstName": "Bob", "employeeId": 103},
{"firstName": "Charlie", "employeeId": 104}
];
for (let member of team) {
console.log(member.firstName);
console.log(member.employeeId);
}
// Converting a JSON string to a JavaScript object
let jsonString = '{"firstName": "David", "employeeId": 105}';
let parsedObj = JSON.parse(jsonString);
console.log(parsedObj.firstName); // David
console.log(parsedObj.employeeId); // 105
Relationship between JSON and JavaScript Objects: JSON is a string representation of a JavaScript object.
// A JavaScript object
let jsObject = {id: 1, status: "active"};
// A JSON string (note the quotes around property names)
let jsonStringRep = '{"id": 1, "status": "active"}';
Conversion Methods:
- JSON string to JS Object:
JSON.parse()let obj = JSON.parse('{"key": "value"}'); - JS Object to JSON string:
JSON.stringify()let jsonStr = JSON.stringify({key: "value"});
Manually constructing JSON strings is error-prone, especially with many fields. Using a library like Gson (for Java) automates conversion between Java objects and JSON.
Using Gson for Backend Serialization:
Frontend (Receiving and Parsing JSON):
<script>
let ajaxReq;
function requestUserData() {
ajaxReq = new XMLHttpRequest();
ajaxReq.open('GET', 'userDataServlet', true);
ajaxReq.onreadystatechange = processResponse;
ajaxReq.send();
}
function processResponse() {
if (ajaxReq.readyState === 4 && ajaxReq.status === 200) {
let responseJson = ajaxReq.responseText;
let userList = JSON.parse(responseJson);
for (let usr of userList) {
console.log(usr.username);
console.log(usr.yearsOld);
console.log(usr.sex);
console.log(usr.joinDate);
}
}
}
</script>
<input type="button" value="Load Users" onclick="requestUserData()">
Backend Servlet with Gson:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
// Assume a User class exists with fields: username, yearsOld, sex, joinDate
@WebServlet("/userDataServlet")
public class UserDataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Create sample data
List<User> users = Arrays.asList(
new User("Alex", 25, "M", new Date()),
new User("Jamie", 30, "F", new Date()),
new User("Casey", 28, "M", new Date())
);
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
// Configure Gson for date formatting and convert list to JSON
Gson gsonConverter = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();
String jsonOutput = gsonConverter.toJson(users);
// Send JSON response
resp.getWriter().print(jsonOutput);
}
}