【发布时间】:2012-05-04 12:23:45
【问题描述】:
我是 java、ajax 和 servlet 的新手。我编写了一个程序,它可以读取用户的输入,并借助一些教程将字典含义打印到网页上。
当我在 servlet 的 doPost 方法中从网页读取输入时,它无法读取并返回 null。也许它正在尝试在提交按钮之前读取输入。我将如何解决这个问题?这是我的jsp文件的相关代码:
function ajaxFunction() {
if(xmlhttp) {
var inword = document.getElementById("inputWord");
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.open("GET","gettime?inputWord="+ inword.value , true ); //gettime will be the servlet name
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
...
<form name="myForm">
Enter the word: <input type="text" name="inputWord" />
<br />
Meaning:<input type="text" name="time" />
<br />
<input type="button" onClick="javascript:ajaxFunction();" value="Click to get the Meaning on Textbox"/>
<br />
</form>
这是我试图在我的 servlet 中获取输入的代码部分:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String inWord = request.getParameter("inputWord"); // word to search in the dictionary
PrintWriter out = response.getWriter();
...
每次我尝试运行项目 request.getParameter("inputWord"); 时都会返回 null。
我在这里尝试了xmlhttp.open("GET","gettime?inputWord="+ inword.value , true ); 的一些代码组合,比如xmlhttp.open("GET","gettime", true );,但没有奏效。
我还在我的 doGet 方法中调用 doPost(request,response);。
感谢任何帮助。
【问题讨论】:
-
你能在没有 AJAX 的情况下让它工作吗?
-
嗯,您在 Ajax 调用中执行 GET 请求,不应触发 doPost。还是您的 doGet 前进到 doPost?
-
字典部分运行良好,但我应该使用 ajax 来完成 :(
-
哦我忘了我打电话给'doPost(request,response); ' 在我的 doGet 方法中