我是ajax概念的新手,我想在不刷新页面的情况下提交表单
AJAX
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Listservlet",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.fname.message.innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
JSP
<form name="fname" action="Listservlet" method="post">
<input type="text" name="txtname" id="txtname" />
<input type="button" value="Submit" onclick="ajaxFunction();" />
<div id="message"></div>
</form>
的servlet
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
String name = null;
PrintWriter out = response.getWriter();
if(request.getParameter("txtname") != null) {
name = request.getParameter("txtname");
}
else {
name = "";
}
out.println("You have successfully made Ajax Call:" + name);
}
这是我从谷歌那里获得的ajax想法,但它没有用, 点击按钮时,没有任何显示。 请帮帮我。
答案 0 :(得分:2)
替换
document.fname.message.innerHTML=xmlhttp.responseText;
通过
document.getElementById("message").innerHTML=xmlhttp.responseText;
答案 1 :(得分:1)
一般步骤找出错误的地方:
对于你的问题,我认为你需要
更改
document.fname.message.innerHTML=xmlhttp.responseText;
到
document.getElementById("message").innerHTML = xmlhttp.responseText;
另请记住关闭您的ouputstream