AJax工作原理
AJax请求的五个步骤
- 创建XMLHttpRequest异步对象
- 设置回调函数
- 使用open方法与服务器建立连接
- 向服务器发送数据
- 在回调函数中针对不同的响应状态进行处理
代码实现
功能需求:
根据用户输入的用户名判断该用户名是否存在(已有用户名存储在数据库中)
代码:
jsp页面
<body>
<form>
请输入用户名:<input type="text" id="userName">
<%-- 提示信息--%>
<span id="tips"></span>
</form>
</body>
ServletAjax页面
@WebServlet("/ServletAjax")
public class ServletAjax extends HttpServlet {
// 调用UserInfoservice中方法
UserInfoService userInfoService = new UserInfoService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置编码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
// 获取请求参数
String userName = req.getParameter("userName");
// 响应回客户端
PrintWriter out = resp.getWriter();
// 如果存在
if (userInfoService.alreadyExist(userName)) {
out.print("用户名可用!");
} else {
out.print("用户名重复!");
}
}
}
UserInfoService中alreadyExist()方法
public boolean alreadyExist(String userName) {
boolean flag = false;
UserInfo userInfo = userInfoDao.alreadyExist(userName);
System.out.println(userInfo);
if (userInfo == null) {
flag = true;
}
return flag;
}
jsp页面中script脚本
<script>
//1.创建XMLHttpRequest对象
var xmlhttp;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp=new XMLHttpRequest();
}
else {
// IE6, IE5 浏览器执行代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
window.onload = function () {
// 绑定监听离焦事件
document.getElementById("userName").addEventListener("blur", function () {
checkName();
});
}
function checkName() {
var name = document.getElementById("userName").value;
// 调用open方法,设置请求的参数传给ServletAjax
xmlhttp.open("POST", "ServletAjax?userName=" + name, true);
xmlhttp.send();
xmlhttp.onreadystatechange=function () {
// 就绪
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// 获取ServletAjax输出文本
var returnString = xmlhttp.responseText;
// 写入提示框
document.getElementById("tips").innerText = returnString;
}
}
}
</script>
指定回调函数:即设定onreadystatechange属性
当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。
下面是 XMLHttpRequest 对象的三个重要的属性:
封装增强版
在jsp页面中添加如下代码
<script>
// 页面加载时,ajax请求servlet获取新闻类别信息
$(function (){
// 参数值设置,key, value的形式
var param = {
option:"getIt"
}
$.ajax({
// 请求方式get或post
type:"get",
// 请求的url地址,对应的ServletNewsType类
url:"ServletNewsType",
// 传递的参数
data:param,
contentType:"text/html;charset=utf-8",
// 回调函数三个参数值,mess为响应回来的信息
success:function(mess, status, xhr) {
console.log("执行到newsType.jsp请求ajax");
// 接收servlet传回的数据并输出
console.log("mess" + mess);
}
});
});
</script>
servlet页面(ServletNewsType类)
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
// 获取jsp页面ajax传递过来的option的值
String option = request.getParameter("option");
if ("getIt".equals(option)) {
getIt(request, response);
}
}
// getIt()方法
protected void getIt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mess = "获取到ServletNewsType中的值了";
// 设置响应格式
response.setContentType("application/json;charset=utf-8");
// 创建Gson对象
Gson gson = new Gson();
String gsonMess = gson.toJson(mess);
// 将mess数据传回jsp页面
response.getWriter().print(gsonMess);
}
测试结果
启动tomcat点击页面打开控制台,从ajax响应再到ajax接收
完~
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/83625.html