This article mainly introduces examples of jQuery Ajax front-end and back-end interaction using JSON. The front-end transmits json to the back-end through jQuery Ajax. The back-end receives json, processes the json, and the back-end returns a json to the front-end. If you are interested, you can Find out more, hope it helps everyone.
Requirements:
The front end transmits json to the back end through jQuery Ajax, the back end receives json, processes the json, and the back end returns a json to the front end
How to use servlet here
1. Use $.post method
index.jsp page
CheckServlet.Java code is as follows
package com.ajax; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CheckServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*设置字符集为'UTF-8'*/ request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String userid = request.getParameter("userid"); // 接收userid String sex = request.getParameter("sex");//接收性别 System.out.println(userid); System.out.println(sex); //写返回的JSON PrintWriter pw = response.getWriter(); String json = "{'success':'成功','false':'失败'}"; pw.print(json); pw.flush(); pw.close(); } }
Since the servlet method is used here, web.xml must be configured
Ajax CheckServlet com.ajax.CheckServlet CheckServlet /Ajax/CheckServlet
Enter an ID on the page, which can be received and printed in the background. The background uses PrintWriter to write back JSON and returns it to the front end. The front end uses eval to convert JSON into an Object object, and obtains the JSON value through obj.name
2. Using the $.get method, you only need to change the post in the jsp page to get
The result is the same as $.post
3. Through the $.ajax method
$.ajax method can also be divided into post and get methods. Modify the sending method by modifying the type
The result is the same as method 1
Related recommendations:
Two methods for javascript to parse url into json format
Completely master the principles and implementation methods of jsonp
The above is the detailed content of Ajax front-end and back-end interaction implementation methods using JSON. For more information, please follow other related articles on the PHP Chinese website!