原生JavaScript实现AJAX(了解)
[案例]
在文本框中输入用户名,当鼠标指针失去焦点时,向Servlet发送Ajax请求。Servlet接收到用户名后进行判断,如果输入的用户名为“江河”,则在span标签中显示“微微一笑很倾城”;如果输入的为其它,则显示“Smile is beautiful”
IDEA文件结构:
ajax_javascript.html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生JavaScript实现AJAX</title>
<script type="text/javascript">
function sendAjax() {
var userName = document.getElementById("username").value;
var xmlhttp;
/ 1.创建ajax对象
if (window.XMLHttpRequest) {
/ IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp = new XMLHttpRequest();
}
else {
/ IE6, IE5 浏览器执行代码
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
/ 2.建立连接
/
* 参数:
* 1.请求方式:GET、POST
* 2.请求的URL(?参数名=参数值)
* 3.同步或异步请求:true为异步,false为同步
*/
xmlhttp.open("post","ajaxServlet?username="+userName,true);
xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded");
/ 3.发送请求
xmlhttp.send();
/ 4.当服务器响应成功后,再获取和处理来自服务器的响应结果
/ 获取方式:xmlhttp.responseText
xmlhttp.onreadystatechange = function() {
/ 判断readyState就绪状态是否为4,判断status响应状态码是否为200
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("msg").innerHTML = xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<form action="" method="">
用户名:<input type="text" name="username" id="username" onblur="sendAjax()"/><span id="msg"></span>
</form>
</body>
</html>
AjaxServlet代码:
package web;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class AjaxServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
String userName = req.getParameter("username");
System.out.println(userName);
if (userName.equals("江河")) {
out.println("微微一笑很倾城");
} else {
out.println("Smile is beautiful");
}
}
}
web.xml代码:
<?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">
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>web.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/ajaxServlet</url-pattern>
</servlet-mapping>
</web-app>
运行结果:
我寻见一片海 碧蓝且耀着光
大片船只航行其上 都向着远方
Shared by Foriver_江河