一個最基礎完整版的ajax專案
阿新 • • 發佈:2018-12-13
jsp檔案
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/9/14
Time: 19:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script type ="text/javascript">
function sendHttpRequest() {
//步驟一建立XMLHttpRequest物件
var xhr = new XMLHttpRequest();
//步驟二設定請求方式及請求路徑
xhr.open("get","AJAXAction");
//步驟三傳送請求
xhr.send();
//步驟四獲取回撥函式
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200){
alert(xhr.responseText);
}
}
}
</script>
</head>
<body>
<input type="button" onclick="sendHttpRequest()" value="準備好開始爽了嗎">
</body>
</html>
java
package com.tjetc.demo;
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 AJAXAction extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
out.print("你通過AJAXAction對我進行了訪問爽了嗎");
}
}
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>AJAXAction</servlet-name>
<servlet-class>com.tjetc.demo.AJAXAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AJAXAction</servlet-name>
<url-pattern>/AJAXAction</url-pattern>
</servlet-mapping>
</web-app>