0

I've been sending data from HTML to my servlet like this :

<form Action="http://caregap2.appspot.com/src.main.java.org.deri.hcls.caregap2.client" Method="GET">
Username: <input type="text" name="username" size="20" value="@gmail">
<BR>
<input type="submit" VALUE="submit">
<input type="reset" value="reset">
</form>

which sends the variable Username to the servlet. But I don't want to have click submit to send the data, I would like to just post the data and load the servlet without clicking anything. I've tried this :

$(document).ready(function() {
var username = "matthewgortnalon@gmail.com";
$.ajax({
      type: "POST",
      url: "http://caregap2.appspot.com/src.main.java.org.deri.hcls.caregap2.client",
      data: { username: "username" }
    }).done(function( msg ) {
     // alert( "Data Saved: " + username );
      window.location = "http://caregap2.appspot.com/src.main.java.org.deri.hcls.caregap2.client?q=" + username;
    });
});

But it doesn't work, can anyone see what I'm doing wrong?? Or if I should use a different method? Help would be really appreciated!! :)

Here's my servlet method :

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");{
        ServletOutputStream  out = response.getOutputStream();
        try {
            out.println("<html><head><title>" +  "</title></head>");
            out.println("<body><h1>" +  "</h1>");
            String  name = request.getParameter("username" );
            //String  comment = request.getParameter( "comment" );
            out.println("Name:" + name + "<BR>");
            //out.println("Comment: " + comment + "<BR>");
        }
        catch(Throwable  t ) {
            out.println("<P><pre>");
            t.printStackTrace( new PrintStream(out) );
            out.println ("</pre><P>");
        }
        out.println ("</body></html>");
    }
4

3 回答 3

3

您的 JSON 数据错误:

data: { "username": username }

首先是键,然后是值(变量)

于 2012-07-12T10:41:27.320 回答
2

好的,我想我知道您要做什么。AJAX 请求不是您想要的。据我了解,您正在尝试加载一个 servlet 并显示它,而根本没有与您的页面进行交互。

您需要做的就是在 javascript 中执行以下操作

var username = "you username here";
window.location = "http://caregap2.appspot.com/src.main.java.org.deri.hcls.caregap2.client?username=" + username;

使用 ajax 请求会将 servlet 主体返回到 done 方法,这对于在当前页面上显示信息而无需重新加载很有用。

您当前正在做的是将 servlet 响应正文附加到查询的末尾,并因此重定向到错误的位置。

额外信息: 使用 Ajax 的替代方法是让您的 servlet 返回一些 html 但不一定返回完整页面,然后使用此响应填充当前页面的一部分。

于 2012-07-12T10:55:05.247 回答
2

您的表单似乎正在使用GET请求,而您的 ajax 正在执行POST请求。您的服务很可能正在寻找GET参数。将 ajax 请求更改为使用GET而不是POST

于 2012-07-12T10:24:08.653 回答