How to call function of JavaScript from servlet

后端 未结 3 1592
遇见更好的自我
遇见更好的自我 2021-01-13 03:14

I am new to web development. I have an external JavaScript file which has a function to show a prompt with error details. I need to pass the error message to the function. I

相关标签:
3条回答
  • 2021-01-13 03:28

    It is not possible to call a java script function from a servlet. Rather, you can print javascript code using

    response.getOutputStream().println("[javascript code]");

    into the browser and then the javascript function will be executed in the browser.

    0 讨论(0)
  • 2021-01-13 03:31

    You need to understand that a servlet runs in the webserver, not in the webbrowser and that JS runs in the webbrowser, not in the webserver. The normal practice is to let the servlet forward the request to a JSP file which in turns produces HTML/CSS/JS code which get sent to the webbrowser by the webserver. Ultimately, all that HTML/CSS/JS code get executed in the webbrowser.

    To achieve your (somewhat strange, tbh) functional requirement, just let the forwarded JSP conditionally render the particular script call. For example as follows with JSTL <c:if>, assuming that you've collected and set the errors as ${errors} in JSON array format:

    <c:if test="${not empty errors}">
        <script>displayErrors(errors);</script>
    </c:if>
    

    Or let JSP assign it as a JS variable and let JS handle it further. Something like:

    <script>
        var errors = ${errors};
    
        if (errors.length) {
            displayErrors(errors);
        }
    </script>
    

    As to the requirement being strange, if you're forced to use JS to display messages, that can only mean that you're using an alert() or something. This is very 90's and not user friendly. Just let JSP produce the HTML accordingly that they're put next to the input fields, or in a list on top of the form. Our servlets wiki page has a hello world example which does exactly like that.

    0 讨论(0)
  • 2021-01-13 03:34

    You can achieve similar kind of behavior by using following method. While sending response itself you can provide JS events.

    PrintWriter out = response.getWriter();
    out.println("<tr><td><input type='button' name='Button' value='Search' onclick=\"searchRecord('"+ argument + "');\"></td></tr>");
    

    So when you click on Search button, search record method of JS will be called.

    0 讨论(0)
提交回复
热议问题