以下是我的代码段
----------输入ajax.html -------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HTML PAGE</title>
<script type="text/javascript">
var request=null;
function createRequest(){
try{
request= new XMLHttpRequest();
)catch(e){
try{
request=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request=null;
}
}
}
if(request==null){
alert("Error Creating Request Object");
}
}
function getName(){
alert("getname called");
createRequest();
var url = "showName-ajax.jsp";
request.open("POST",url,true);
alert("before");
request.onreadystatechange = updatePage;
alert("after");
request.send(null);
}
function updatePage(){
//var newName= request.getResponseHeader("r1");
var newName= request.responseText;
var name1 = document.getElementById("name");
replaceText(name1,newName);
}
function replaceText(el, text) {
if (el != null) {
clearText(el);
var newNode = document.createTextNode(text);
el.appendChild(newNode);
}
}
function clearText(el) {
if (el != null) {
if (el.childNodes) {
for (var i = 0; i < el.childNodes.length; i++) {
var childNode = el.childNodes[i];
el.removeChild(childNode);
}
}
}
}
</script>
</head>
<body>
<h1>WELCOME <span id="name"> GUEST</span></h1>
<form method="POST">
<input type="text" name="t1">
<input type="button" value="Show Name" onclick="getName();"/>
</form>
</body>
</html>
---------- showName-ajax.jsp ------------
<%
String s1=request.getParameter("t1");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(s1); // Write response body.
%>
但是当我运行程序时(单击按钮)没有任何反应。甚至不会出现调用getName函数的警报消息。请帮助!!!!
答案 0 :(得分:0)
错字:
)catch(e){
应该是
}catch(e){
这会在浏览器的控制台中显示为错误。如果事情不能正常工作,请务必先检查一下。
答案 1 :(得分:0)
你有a)而不是}}:
try{
request= new XMLHttpRequest();
)catch(e){
所以你的函数永远不会被定义。
答案 2 :(得分:0)
change )catch(e){ to }catch(e){
但 你为什么每次点击按钮创建请求对象? 你只需要在页面加载事件上调用“createRequest()”一次。