开发者

How to get jQuery, AJAX and a servlet working together?

开发者 https://www.devze.com 2023-02-19 21:42 出处:网络
I am extremely new to jQuery and AJAX, however after 7 hours of reading tutorials and playing with code, I have an ok understanding of exactly how they work. This is what I am trying to accomplish....

I am extremely new to jQuery and AJAX, however after 7 hours of reading tutorials and playing with code, I have an ok understanding of exactly how they work. This is what I am trying to accomplish....

I have a web application that allows a user to register with the site. I would like to have the userName that they enter (in the registration page) checked asynchronously for existence in the database. Seems pretty straight forward but I have not been having luck.

This is the jQuery that I have written....

$(document).ready(function() {
        $("a").click(function(){
            alert("Should be going to servlet now");
            $.ajax({
                type: 'GET',
                url: "checkName",
                data: {userName: "Hexose"},
                success: function(data){ alert(data);}
            });
        });

    });

I am using static data right now for debugging purposes as I am having another issue getting the value from the form field. I also dont really understand the success: function part, what is "data" as the parameter to the function? Does that come in the response?

Now I have a servlet mapped to "checkName" and the servlet works (I debugged and passed parameter by URL). Here is the servlet code...

public class CheckUserNameServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

    String targetUN = request.getParameter("userName");

    if (data.UserDB.userNameExists(targetUN)) {
        String exists = "Username already taken...";
        response.setContentType("text");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(exists);
        response.setStatus(200);
    } else {
        respon开发者_JAVA技巧se.getWriter().write("Username is available...");
    }
}

}

I know that my call to the database returns what I need, but I suspect that something in this servlet is wrong. And for good measure here is the element where the data is supposed to be coming from

<tr>
  <td align="right">Username:</td>
  <td><input type="text" name="userName" id="userName" value="${user.userName}"  /</td>
  <td><span id="exist"> <a href="">Check Availability</a></span></td>
</tr>

So essentially my questions are this.... 1. Am I using the jQuery correctly, using the .ajax and whatnot? Is there an easier way to do it or another method which is cleaner? 2. Is there something wrong in my servlet? I feel like the response is not correct or I have coded that incorrectly. 3. How am I supposed to go about getting the value form the userName element? I have used $("#userName").val() and it always give and empty string or null.

Any pointers or tips or anything at this point would be greatly appreciated, I am kind of losing my mind on this one. Also if I am completely off on any of this feel free to just point me toward a good tutorial.

Thanks in advance.

EDIT: So the ID of the userName element was my problem. I changed the ID and now the whole thing works. One follow up question though. Is there a way to stop form submission if the response comes back and says that the userName is taken?


1. jQuery ajax()

In JavaScript, you can't really spawn new threads - the closest you can get to that is using setTimeout() or setInterval(). What this means is that operations that take a long time (like fetching data over the network) will block everything else. So you'll often see callback functions being used (this takes advantage of the fact that functions are first-class members in JavaScript).

The success parameter to the ajax() function is exactly that, a callback function that will invoked when the request completes successfully - by default, ajax requests are asynchronous so you need something to hook into to be informed when the action is completed. Think of it somewhat like registering a listener in Swing, if you've ever used it. The success function will be invoked with certain arguments (remember, JavaScript supports var-args), the first of which is the data that was received as the response. If jQuery can identify the data type correctly (or if you set the dataType parameter in the call to ajax()), data will be the parsed response made available for use.

A shorthand that you could use in this case is the jQuery get() - it uses ajax() internally but gives you a simpler function call to use to make GET requests

Also, as noted by others, you should attach your click event handler to more specific elements and for a elements, it's usually a good idea to prevent the default (event.preventDefault()) so that the browser doesn't follow the link.

You might want to use Firebug for Firefox - it provides a console object where you can log data - console.log("Response: ", data) will print out the contents of data to the console and if it's an object (like a JSON response), it'll even appear in a hierarchical manner that you can explore. It's much better than a bunch of alert()'s which block execution until you click ok and much less annoying.

2. Servlet

Why do you think there's a problem? Your servlet looks fine except for perhaps some unnecessary things (like setting the status code to 200). Also, you might want to change the content-type to text/plain which is the usual MIME-type for plain text. Later, you could probably look into JSON and send back a JSON response so you could pack in more information into your response (like say suggested usernames when the requested username is not available) in a structured fashion that can be easily used by the JavaScript on the client side.

3. Getting the text field value

This also looks fine - $("#userName").val(). You can use Firebug to also explore the current DOM and see what the value of the text field is set to. There is one problem with your code but I'm not sure if you made a mistake while pasting it here or if it's an actual issue in the code. You're missing the closing angle-bracket > before </td>

<td><input type="text" name="userName" id="userName" value="${user.userName}" /</td>


  1. Your jquery seems correct although you probably didn't want to attach the same click handler to all anchors on your page. :) The way you are using jquery for ajax calls is just fine. There are many situations in which you want to get json as response from server and in that case you'll use option: dataType: "json", and parameter data that comes to success handler will be javascript object (in case you have properly set up response type in servlet with something like: response.setContentType("application/json");

  2. Try with firebug to check if you are actually making a call to server and to see what you get as response from it. (since you said it works when you try it with browser)

  3. $('#userName").val() should work. But I am not sure whether you properly initialize your ${user.userName} value which you use for populating the value to that field. Did you try populating the field yourself?


Firstly a possible problem, you are adding a jQuery .click() handler to ALL anchor tags <a ....></a>, a much better way would be in this case to listen to anchor tags inside the exist span:

$("#exist a").click(........

Secondly with your jQuery, you are not telling the browser not to do what it is supposed to be doing. What I mean here is, if someone clicks on an anchor tag, the browser understands it is supposed to follow it - a blank href will reload the page.
This action can be stopped very easily:

$("a").click(function(e){
    e.preventDefault();
    ...........

As for data in success that is what is passed to the function when the ajax call returns. This can be many things, text, html or json. So in the case of your servlet it looks like its going to be text, and that should either be Username already taken... or Username is available...

This is correct for getting the value of your input field, but it looks like, if you copied and pasted your HTML, you are missing a closing > from your input field for the userName

$("#userName").val()
0

精彩评论

暂无评论...
验证码 换一张
取 消