简体   繁体   中英

jQuery AJAX call to sevlet not working in anchor tag

I am new to jQuery and Servlets. Working on a school project and now I am stuck at this problem.

I have a navigation bar on left with anchor tags like this in my proj3.html file.

  <ul class="nav nav-list">

          <li class="nav-header">Labels</li>
          <li><a href="" class="labels">Sony</a></li>
          <li><a href="" class="labels">Spinnin</a></li>
          <li><a href="" class="labels">BMG</a></li>
          <li><a href="" class="labels">Ultra</a></li>
      <li><a href="" class="labels">Universal</a></li>

          <li class="nav-header">Genere</li>
          <li><a href="" class="genere">Rock</a></li>
          <li><a href="" class="genere">Alternative Rock</a></li>
          <li><a href="" class="genere">Pop</a></li>
          <li><a href="" class="genere">EDM</a></li>
          <li><a href="" class="genere">Hip-Hop</a></li>
       </ul>

Inside Javascript i have this

 $('a.labels').on('click',function(e){

        var url = "http://example.edu/servlet/SampleQuery";       
            $.get(url);
        e.preventDefault();
    }

}

Inside my servlet SampleQuery.java I read from DB and forward to a JSP like this

       RequestDispatcher dispatcher = null;
       dispatcher = request.getRequestDispatcher("/jsp/DisplayVendor.jsp"); 
   dispatcher.forward(request, response);

When I click on any of the anchor tags $.get is hit, but my JSP page is not getting displayed. Weird thing is if I check the firebug for network traffic I see my AJAX call going through and I can even see DisplayVendor.jsp page in response. But its not getting displayed.

Can someone please point out if I am making any mistake.

Thanks

You call $.get(url) , but don't do anything with the response. Change it to

$.get(url, function(data) {
    alert('here is the response data : ' + data);
});

to show what you received.

To update the contents of the div with id "dynamicallyLoadedDiv" with the HTML returned by the AJAX call, for example, use

$.get(url, function(data) {
    $('#dynamicallyLoadedDiv').html(data);
});

or simply

$('#dynamicallyLoadedDiv').load(url);

Read the documentation for more information.

Note that if your goal is to replace the whole page content, I don't really seee the point of making an AJAX request. Use a simple hyperlink in that case.

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