載入時運行了一次,之後失效了,代碼如下
add.jsp
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/x-icon" href="../favicon.ico" />
<title>添加</title>
<link href="/IMS/css/css.css" rel="stylesheet" type="text/css">
<script src="/IMS/lib/MakeRequest.js"></script>
<script>
window.onload = initForm;
function initForm() {
makeRequest(document.getElementById("aname"));
}
</script>
</head>
<body>
<form action="Department111" method="post" name="add" id="add">
<input type="hidden" name="action" value="add">
<table>
<tr>
<td width="120" align="right">名稱:</td>
<td width="180" align="left"><input name="aname" type="text" id="aname" autofocus="autofocus" date="Department?action=s&name=" class="reqd"></td>
</tr>
<tr>
<td align="right">權限:</td>
<td align="left"><input name="level" id="level" class="reqd"></td>
</tr>
<tr>
<td align="right">
<a href="index.jsp">返回</a>
</td>
<td align="left"><input name="add" type="submit" id="add" value="添加"></td>
</tr>
</table>
</form>
</body>
</html>
MakeRequest.js
function makeRequest(obj) {
obj.addEventListener("onchange", makeR(obj), false)
function makeR(obj) {
console.log(obj);
var url = obj.getAttribute("date") + obj.value;
console.log(obj.value);
console.log(url);
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
console.log(e);
}
}
}
if (xhr) {
xhr.addEventListener("readystatechange", showContents, false);
xhr.open("GET", url, true);
xhr.send(null);
} else {
msg.innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseXML.getElementsByTagName("s")[0].childNodes[0].nodeValue;
if (outMsg == "yes") {
alert("已存在");
}
} else {
var outMsg = "There was a problem with the request "
+ xhr.status;
alert(outMsg);
}
}
}
}
}
obj.addEventListener("onchange", makeR(obj), false)
==>
obj.addEventListener("change", function(){makeR(obj)}, false)