同步和异步:
代码演示如下:
服务端:AjaxServlet:
package com.itheima.web.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 响应给客户端数据
response.getWriter().write("hello ajax~");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
客户端:
Title
注意细节:
1、发送请求的地址要是总的URL地址
2、默认为true 异步
3、客户端的三个步骤可以在 网站获取(直接复制代码即可)w3school 在线教程全球最大的中文 Web 技术教程。https://www.w3school.com.cn/
开启服务器访问客户端演示结果:
代码演示如下:
服务端:SelectUserServlet
package com.itheima.web.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/selectUserServlet")
public class SelectUserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1 接收用户名参数
String username =request.getParameter("username");
// 2 调用service查询User对象
// (我们这里定义一个变量为true假设查询的User用户名是存在的)
boolean flag =true;
// 3 响应给前端标记(假设我们这里响应 “true”)
response.getWriter().write("" + flag); // 这里其实响应的是字符串型的true (因为空串 + 字符型true)
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
客户端(前端):register.html
注意1:重点代码在ajax请求部分(要看的懂)
注意2:要在