我正在使用XMLHttpRequest从servlet创建一个简单的表单submit和get会话变量。但似乎没有任何效果。有人可以指出我哪里出错了吗?
这是表格
<form method="post" target="_self" action="/temp/Welcome.html">
<table>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email" value="a@a.com"></td>
</tr>
<tr>
<td>Project ID</td>
<td><input type="text" id="projectid" name="projectid" value="1111"></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="button" id="submitbutton" value="Submit" onclick="submitLogin()"></td>
</tr>
</table>
</form>
这是submitLogin函数
function submitLogin()
{
var url_action="/temp/Login";
var client;
var dataString;
if (client.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
client=new XMLHttpRequest();
} else { // IE6, IE5
client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange=function(){
alert(client.responseText);
if(client.readyState==4&&client.status==200)
{
alert(client.responseText);
}
else
alert("Error: return status code "+client.status+" "+client.statusText);
};
dataString="email="+document.getElementById("email").value;
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(dataString);
}
和我在Login.java servlet中的post方法
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
paramMap=request.getParameterMap();
if (paramMap == null)
throw new ServletException(
"getParameterMap returned null in: " + getClass().getName());
iterator=paramMap.entrySet().iterator();
//System.out.println(paramMap.size());
String str="";
while(iterator.hasNext())
{
Map.Entry me=(Map.Entry)iterator.next();
String[] arr=(String[])me.getValue();
emailId=arr[0];
//System.out.println(me.getKey()+" > "+emailId);
}
rand=new Random();
randomInt=rand.nextInt(1000000);
emailId=randomInt+emailId;
System.out.println(emailId);
out.println(emailId);
/*creates a new session if a session does not exist already*/
session=request.getSession();
session.setAttribute("uid", emailId);
out.close();
}
所有警报和System.out似乎都没有显示任何响应。请指导我。感谢
注意:在IE 8中,它显示xmlhttprequest为null或不是对象,login.js在第7行
答案 0 :(得分:4)
看起来你的Java脚本中有一个简单的拼写错误
var client;
if (client.XMLHttpRequest){
client=new XMLHttpRequest();
} else {
client=new ActiveXObject("Microsoft.XMLHTTP");
}
您正在声明一个名为client的变量,并要求它为XMLHttpRequest成员。你可能想要使用window.XMLHttpRequest。
答案 1 :(得分:0)
抱歉,我的不好。这是if (window.XMLHttpRequest)
而不是if (client.XMLHttpRequest)
现在可以正常工作。