AJAX学习笔记2发送Post请求_biubiubiu0706的博客-CSDN博客
1.验证用户名是否可用
需求,用户输入用户名,失去焦点-->onblur失去焦点事件,发送AJAX POST请求,验证用户名是否可用
新建表
前端页面
WEB-INF下新建lib包引入依赖,要用JDBC
后端代码
package com.web;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;
import java.io.PrintWriter;
import java.sql.*;/*** @author hrui* @date 2023/9/3 22:11*/
@WebServlet("/checkusername")
public class AjaxRequestCheckName extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//获取用户名String username = req.getParameter("username");//打布尔标记(一种编程模型)boolean flag=false;//连接数据库校验用户名是否存在Connection conn=null;PreparedStatement ps=null;ResultSet rs=null;//1.注册驱动//System.setProperty("jdbc.drivers","com.mysql.cj.jdbc.Driver");try {Class.forName("com.mysql.cj.jdbc.Driver");//2.获取连接conn= DriverManager.getConnection("xxx", "xxx", "xxx");//3.获取执行对象String sql="select id,name from t_user where name=?";ps = conn.prepareStatement(sql);ps.setString(1, username);//4.执行sqlrs = ps.executeQuery();//5.处理结果集if(rs.next()){//如果只有一条的情况//用户名存在flag=true;}} catch (Exception e) {e.printStackTrace();}finally {if(rs!=null){try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if(ps!=null){try {ps.close();} catch (SQLException e) {e.printStackTrace();}}if(conn!=null){try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}//响应结果到浏览器resp.setContentType("text/html;charset=utf-8");PrintWriter writer = resp.getWriter();if(flag){writer.print("<font color='red'>用户名存在,不可用</font>");}else{writer.print("<font color='green'>用户名可用</font>");}}public static void main(String[] args) {try {//Class.forName("com.mysql.cj.jdbc.Driver");Connection conn= DriverManager.getConnection("xxx", "xxx", "xxx");System.out.println(conn);} catch (Exception e) {e.printStackTrace();}}
}
还可以在input获得焦点时候对<span里面的数据清空
其实和input里面直接写 οnfοcus="xxx方法" 一样
2.用户点击按钮,发送AJAX请求 显示学院列表
测试
现在这种情况存在的问题是是后端代码又开始拼接HTML
能不能直接返回数据,剩下让前端处理 可以返回JSON 或者 XML
返回JSON数据
回顾JSON
也可以是这样
测试
上面是在JS代码中创建JSON对象,数组的访问
但是在后端返回前端时候,永远返回的都是字符串--->如何将JSON字符串转换为JSON对象呢
测试
下面后端就用JSON格式字符串的方式返回数据
下面去连接下数据库
前端
后端
package com.web;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;
import java.io.PrintWriter;
import java.sql.*;/*** @author hrui* @date 2023/9/3 23:57*/
@WebServlet("/studys")
public class AjaxRequestStudys extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//连接数据库,查询学院resp.setContentType("text/html;charset=utf-8");PrintWriter writer = resp.getWriter();StringBuilder builder=new StringBuilder();String jsonStr="";// builder.append("<tr>");
// builder.append("<td>1</td>");
// builder.append("<td>张三</td>");
// builder.append("<td>20</td>");
// builder.append("<td>北京大兴区</td>");
// builder.append("</tr>");
// builder.append("<tr>");
// builder.append("<td>2</td>");
// builder.append("<td>李四</td>");
// builder.append("<td>22</td>");
// builder.append("<td>北京海淀区</td>");
// builder.append("</tr>");//拼接一个JSON数组回去//builder.append("[");//用''单引号也不行 前端解析不了
// builder.append("{'id':1,'name':'张三','age':20,'addr':'北京大兴区'},");
// builder.append("{'id':2,'name':'李四','age':22,'addr':'北京海淀区'}");
// builder.append("{\"id\":1,\"name\":\"张三\",\"age\":20,\"addr\":\"北京大兴区\"},");
// builder.append("{\"id\":2,\"name\":\"李四\",\"age\":22,\"addr\":\"北京海淀区\"}");//连接数据库校验用户名是否存在Connection conn=null;PreparedStatement ps=null;ResultSet rs=null;//1.注册驱动//System.setProperty("jdbc.drivers","com.mysql.cj.jdbc.Driver");try {Class.forName("com.mysql.cj.jdbc.Driver");//2.获取连接conn= DriverManager.getConnection("xxx", "xxx", "xxx");//3.获取执行对象String sql="select id,name,age,addr from t_stu";ps = conn.prepareStatement(sql);//4.执行sqlrs = ps.executeQuery();//5.处理结果集builder.append("[");while(rs.next()){//如果只有一条的情况String id = rs.getString("id");String name = rs.getString("name");String age = rs.getString("age");String addr = rs.getString("addr");//{"id":1,"name":"zhangsan","age":13,"addr":"北京大兴区"}builder.append("{\"id\":"+id+",\"name\":\""+name+"\",\"age\":"+age+",\"addr\":\""+addr+"\"},");}//去掉最后一个{},后面的逗号jsonStr=builder.substring(0, builder.length()-1)+"]";} catch (Exception e) {e.printStackTrace();}finally {if(rs!=null){try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if(ps!=null){try {ps.close();} catch (SQLException e) {e.printStackTrace();}}if(conn!=null){try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}writer.print(jsonStr);}
}
测试
这样拼接JSON太麻烦 使用fastjson对程序进行改进
引入jar包
不需要那么麻烦进行拼接
package com.web;import com.alibaba.fastjson.JSON;
import com.pojo.Student;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;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;/*** @author hrui* @date 2023/9/3 23:57*/
@WebServlet("/studys")
public class AjaxRequestStudys extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//连接数据库,查询学院resp.setContentType("text/html;charset=utf-8");PrintWriter writer = resp.getWriter();
// StringBuilder builder=new StringBuilder();
// String jsonStr="";List<Student> list=new ArrayList<>();// builder.append("<tr>");
// builder.append("<td>1</td>");
// builder.append("<td>张三</td>");
// builder.append("<td>20</td>");
// builder.append("<td>北京大兴区</td>");
// builder.append("</tr>");
// builder.append("<tr>");
// builder.append("<td>2</td>");
// builder.append("<td>李四</td>");
// builder.append("<td>22</td>");
// builder.append("<td>北京海淀区</td>");
// builder.append("</tr>");//拼接一个JSON数组回去//builder.append("[");//用''单引号也不行 前端解析不了
// builder.append("{'id':1,'name':'张三','age':20,'addr':'北京大兴区'},");
// builder.append("{'id':2,'name':'李四','age':22,'addr':'北京海淀区'}");
// builder.append("{\"id\":1,\"name\":\"张三\",\"age\":20,\"addr\":\"北京大兴区\"},");
// builder.append("{\"id\":2,\"name\":\"李四\",\"age\":22,\"addr\":\"北京海淀区\"}");//连接数据库校验用户名是否存在Connection conn=null;PreparedStatement ps=null;ResultSet rs=null;String s="";//1.注册驱动//System.setProperty("jdbc.drivers","com.mysql.cj.jdbc.Driver");try {Class.forName("com.mysql.cj.jdbc.Driver");//2.获取连接conn= DriverManager.getConnection("xxx", "xxx", "xxx");//3.获取执行对象String sql="select id,name,age,addr from t_stu";ps = conn.prepareStatement(sql);//4.执行sqlrs = ps.executeQuery();//5.处理结果集//builder.append("[");while(rs.next()){//如果只有一条的情况String id = rs.getString("id");String name = rs.getString("name");String age = rs.getString("age");String addr = rs.getString("addr");//{"id":1,"name":"zhangsan","age":13,"addr":"北京大兴区"}//builder.append("{\"id\":"+id+",\"name\":\""+name+"\",\"age\":"+age+",\"addr\":\""+addr+"\"},");Student stu=new Student(id,name,age,addr);list.add(stu);}//去掉最后一个{},后面的逗号//jsonStr=builder.substring(0, builder.length()-1)+"]";s = JSON.toJSONString(list);} catch (Exception e) {e.printStackTrace();}finally {if(rs!=null){try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if(ps!=null){try {ps.close();} catch (SQLException e) {e.printStackTrace();}}if(conn!=null){try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}writer.print(s);}
}
测试
下面用XML进行数据交互(XML体积大,现在相对用的少)
后端代码 注意下Content-Type
@WebServlet("/xmlstudys")
public class AjaxRequestXML extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//注意响应类型是XMLresp.setContentType("text/xml;charset=utf-8");PrintWriter writer = resp.getWriter();StringBuilder xml=new StringBuilder();/*XML格式<Students><Student><id>1</id><name>张三</name><age>22</age><addr>北京大兴区</addr></Student><Student><id>2</id><name>李四</name><age>23</age><addr>北京海淀区</addr></Student></Students>*/xml.append("<Students>");xml.append("<Student>");xml.append("<id>1</id>");xml.append("<name>张三</name>");xml.append("<age>22</age>");xml.append("<addr>北京大兴区</addr>");xml.append("</Student>");xml.append("<Student>");xml.append("<id>2</id>");xml.append("<name>李四</name>");xml.append("<age>23</age>");xml.append("<addr>北京海淀区</addr>");xml.append("</Student>");xml.append("</Students>");writer.print(xml);}
}
前端代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>使用XML完成数据交互</title>
</head>
<body>
<script type="text/javascript">window.onload=function(){document.getElementById("btn").onclick=function(){var xhr=new XMLHttpRequest();xhr.onreadystatechange=function (){if(this.readyState==4){if(this.status==200){//服务器响应XML字符串,如何接收//使用XMLHTTPRequest的responseXML属性,接收之后,自动封装成document对象(文档对象)var xmlDoc=this.responseXML;console.log(xmlDoc)}else{}}}xhr.open("get","/ajax/xmlstudys",true)//xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")xhr.send()}}
</script><input type="button" value="显示学生列表" id="btn"><table width="50%" border="1px"><tr><th>序号</th><th>姓名</th><th>年龄</th><th>住址</th></tr><tbody id="stubody"><!-- <tr>--><!-- <td>1</td>--><!-- <td>张三</td>--><!-- <td>20</td>--><!-- <td>北京大兴区</td>--><!-- </tr>--><!-- <tr>--><!-- <td>2</td>--><!-- <td>李四</td>--><!-- <td>22</td>--><!-- <td>北京海淀区</td>--><!-- </tr>--></tbody>
</table>
</body>
</html>
测试
具体前端代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>使用XML完成数据交互</title>
</head>
<body>
<script type="text/javascript">window.onload=function(){document.getElementById("btn").onclick=function(){var xhr=new XMLHttpRequest();xhr.onreadystatechange=function (){if(this.readyState==4){if(this.status==200){//服务器响应XML字符串,如何接收//使用XMLHTTPRequest的responseXML属性,接收之后,自动封装成document对象(文档对象)var xmlDoc=this.responseXML;console.log(xmlDoc)//获取所有<student>元素,返回了多个对象,是个数组var students=xmlDoc.getElementsByTagName("student")console.log(students[0].nodeName)var html=""for(var i=0;i<students.length;i++){var stu=students[i]//获取<student>节点下所有子元素var s=stu.childNodes;html+="<tr>"for(var j=0;j<s.length;j++){var node=s[j]if(node.nodeName=="id"){console.log("id="+node.textContent)html+="<td>"+node.textContent+"</td>"}if(node.nodeName=="name"){console.log("name="+node.textContent)html+="<td>"+node.textContent+"</td>"}if(node.nodeName=="age"){console.log("age="+node.textContent)html+="<td>"+node.textContent+"</td>"}if(node.nodeName=="addr"){console.log("addr="+node.textContent)html+="<td>"+node.textContent+"</td>"}}html+="</tr>"}document.getElementById("stubody").innerHTML=html}else{}}}xhr.open("get","/ajax/xmlstudys",true)//xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")xhr.send()}}
</script><input type="button" value="显示学生列表" id="btn"><table width="50%" border="1px"><tr><th>序号</th><th>姓名</th><th>年龄</th><th>住址</th></tr><tbody id="stubody"><!-- <tr>--><!-- <td>1</td>--><!-- <td>张三</td>--><!-- <td>20</td>--><!-- <td>北京大兴区</td>--><!-- </tr>--><!-- <tr>--><!-- <td>2</td>--><!-- <td>李四</td>--><!-- <td>22</td>--><!-- <td>北京海淀区</td>--><!-- </tr>--></tbody>
</table>
</body>
</html>