0
所以,我想學習AJAX,我想製作一個相同的應用程序,如in here ,我幾乎複製它,但它不起作用。我不知道爲什麼,我試圖自己解決它,但找不到任何解決方案。無法設置null的屬性'innerHTML'。問題與AJAX(java)
我的.js文件是:
function ajaxAsyncRequest(reqURL) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", reqURL, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// How to get message
alert('It\'s K');
document.getElementById("message").innerHTML = xmlhttp.responseText;
alert(xmlhttp.responseText);
} else {
alert('Something is wrong !');
}
}
};
xmlhttp.send(null);
}
指數.JSP是:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="javascript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="Show Server Time" onclick='ajaxAsyncRequest("getTime")' />
</body>
</html>
和我的servlet代碼是:
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/getTime")
public class GetTimeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetTimeServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
PrintWriter out = response.getWriter();
LocalDate currentTime= LocalDate.now();
String message = "Currently time is "+currentTime.toString();
out.write(message);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
但是當我按一下按鈕我收到了我在.js文件中document.getElementById("message").innerHTML = xmlhttp.responseText;
行中的標題中指出的消息。 我正在運行它http://localhost:8080/HelloAjax/
,所以沒有本地,它加載比頁面晚,所以我不知道它是什麼。
哇,謝謝,我對html有一個很差的認識 – user3212350