Below, there is jquery script which calls Servlet by URL. At first i need to say that i have 2 separate projects. First is Dynamic Web Project which contains servlets etc. Second is simple Ratchet HTML-CSS-JS Project which of course contains some pages, scripts and css.
<script>
$(document).ready(function() { // When the HTML DOM is ready loading, then execute the following function...
$('#button').click(function() { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('http://localhost:8080/testuje/text', function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
$('#div').text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
});
</script>
Here is my Servlet code:
package pl.javastart.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/text")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text);
// Write response body.
}
}
The problem is, what should i put in $.get('http://localhost:8080/testuje/text', function(responseText)
to get servlet content after button click.
Aucun commentaire:
Enregistrer un commentaire