简体   繁体   中英

Jquery getJSON not working with Spring MVC

Following code is not able to submit the request to server and I am unable to figure out why.

here is part of my jsp page

 $(document).ready(function() {
    $('#firstName').change(function() {
        if(('#firstName').val().length >= 2){
                $.getJSON(
                   "getPSPersons.html", 
                   { firstName: $('#firstName').val(), lastName: $('#lastName').val()},
                   function(data) {
                     buildTable(data);
                   }
                );
         }
     });
  });
   -------------------------------
 <form:form name="addperson" method="GET">
      <label for="firstName">First Name</label> &nbsp;
      <input type="text" name="firstName" id="firstName" size="15"/>  &nbsp; &nbsp;
      <label for="lastName">Last Name</label> &nbsp;
      <input type="text" name="lastName" id="lastName" size="15"/>
  </form:form>

And the Spring controller class function

   @RequestMapping(value="getPSPersons.html", method = RequestMethod.GET)
   public @ResponseBody List<Person> getPersonsWithNames(
         @RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName) 
   {
       List<Person> personList = new ArrayList<Person>();
          if(firstName.length()>=2 || lastName.length() >=2)
    {
                 personList = personService.getPersonsWithName(firstName, lastName);
    }
          return personList;
    }

requirement is that when the user enter more than one character in "firstname" input box, an AJAx request should be submitted to the server to get all persons whose firstname starts with those letters...but here the get request never calls this functions.. I am pretty sture something's wrong on JQuery request side but I can't find what it is..

-----update---------

found the error.. on line 3 it should have been if( $ ('#firstName').val().length >= 2){ that $ at the beginning was missing

If you'd like, rather than re-inventing the wheel, why don't you use a pre-existing autosuggest widget - there are quite a few written in JQuery. I just love this one: http://code.drewwilson.com/entry/autosuggest-jquery-plugin - give it a try.

i find a js error.

('#firstName').val().length

it must be

$('#firstName').val().length

or

$(this).val().length

you lost the "$",fixed it,i found request was sended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM