ajax 入门
ajax发送post请求和发送get请求的一些区别:
当ajax使用post提交请求时,设置中文乱码的情况需要额外处理
同时post请求的参数在请求体里,所以参数应该写在send里,而get的参数直接写在url里,所以send里是空的
https://blog.csdn.net/qq_38499084/article/details/79699210 可看这篇博客
为了防止ajax的get请求走浏览器缓存的解决方法:在get 的url处加时间戳
应用:模拟表单填写,当用户名一栏失去焦点时,ajax向后台发送请求,后台判断用户名是否已被注册
返回的结果在网页上进行局部刷新,提示用户
index.jsp
<%-- Created by IntelliJ IDEA. User: ASUS Date: 2020/4/16 Time: 22:56 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <script type="text/javascript"> function checkUsername(username) { // 1.创建Ajax核心对象,浏览器内置,可以直接使用 var xhr = new XMLHttpRequest(); // 2.注册回调函数 xhr.onreadystatechange = function (ev) { // 服务器返回响应 if(xhr.readyState == 4){ if(xhr.status == 200){ var msg = document.getElementById("nameTipMsg"); msg.innerHTML = xhr.responseText; }else { alert(xhr.status); } } } // 3.开启浏览器和服务器之间的通道 xhr.open("GET","/myWeb/checkusername.do?username="+username,true); // 4.发送Ajax请求 xhr.send(); } </script> 用户名:<input type="text" name="username" onblur="checkUsername(this.value);"> <span id="nameTipMsg" style="font-size: 12px"></span><br> 密码:<input type="password" name="password"><br> </body> </html>
OneServlet
public class OneServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.获取用户名 String username = req.getParameter("username"); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); // 2.验证用户名 if("admin".equals(username)){ // 用户名不可用 out.print("<font color='red'>用户名已被注册</font>"); }else { // 用户名可用 out.print("<font color='green'>用户名可用</font>"); } } }
web.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>OneServlet</servlet-name> <servlet-class>com.controller.OneServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OneServlet</servlet-name> <url-pattern>/checkusername.do</url-pattern> </servlet-mapping> </web-app>