简体   繁体   中英

JSP - SERVLET - calling a javascript function from a servlet

i have a simple JSP page that calls a servlet on a click of a button and then the servlet call some internal methods to perform a task and then the time comes when the servlet action comes to an end and the goal now is, at the end of the servlet function, i want to return the control to the jsp page and soon execute a java script (there will be no event triggered, as soon as the control comes to teh jsp, the Javascript should run). how can i achieve this. as far as i have googled, it is impossible to call a javascript without any event(like a click, hover, etc) being triggered. is there a way to achieve my goal?

UPDATE

<form action="http://localhost:90/Jdfront1/hello" onsubmit="return validate()">

<label>Topic :</label><input type="text" name="topic" id="topic"/><br>
<label>Number of pages :</label><input type="text" name="Nopages" id="Nopages"/><br>
<label>URL :</label><input type="text" name="link" id="link"/><br>
<label>isRange :</label><input type="text" name="range" id="range"/><br>
<input type="submit" value="click here!!" >

this is the form i have.

Use AJAX to invoke the Servlet, then use the success handler to invoke your JS function.

You can use jQuery to easily do this:

$("#button-id").click(function() {
    $.ajax({
        url: "/url?topic="+$('#topic').val()+'&Nopages='+$('#Nopages').val()+'&link='+$('#link').val()+'&range='+$('#range').val(),
    })
    .done(function( data ) {
        // Invoke your function here
        validate();
    });
});

See https://api.jquery.com/jQuery.ajax/ for more details.

Server-side, you can use http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String) to get the query string parameters and process them.

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