Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending dynamically generated javascript file

Background:

I have a servlet in which I am dynamically generating javascript and putting into a variable script. Then I set the response content type as text/javascript and send the script over to the client:

resp.setContentType("text/javascript");
resp.getWriter().println(script);

Problem:

The browser does download the javascript file but it doesn't recognize the functions inside the file. If I create a static javascript file and use it instead, it works fine.

Question:

What should be done so that browser treats response from the servlet as a regular javascript file?

Thank you for help.

like image 884
craftsman Avatar asked May 27 '11 18:05

craftsman


2 Answers

It should work fine. I suspect that you're just including it the wrong way or calling the function too early or that the response content is malformed.

I just did a quick test:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 6156155</title>
        <script src="javaScriptServlet"></script>
        <script>test()</script>
    </head>
    <body>
    </body>
</html>

with

@WebServlet(urlPatterns={"/javaScriptServlet"})
public class JavaScriptServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/javascript");
        response.getWriter().write("function test() { alert('peek-a-boo'); }");
    }

}

and I get

Screenshot of browser alert showing "peak-a-boo" message in it.

like image 120
BalusC Avatar answered Nov 16 '22 16:11

BalusC


How do you refer to this servlet from your browser ?

If you want to include this with a HTML page (existing one), you should refer to it from the tag of your page.

Ex.

<html>
<head>
<script type='text/javascript' src='URL_TO_YOUR_SERVLET'></script>
</head>
</html>

Or if you want it to be executed as part of a Ajax call, just pass the response to eval function.

Or else, if you just want to send the output and get it executed in browser, you need to send the HTML segment as well. Then include your JS with in the body tags, as a script tag.

ex. Your servlet sends the following, using content type 'text/html' :

<html>
<body>
 <script type='text/javascript'>
     <!-- write your generated JS here -->
 </script>
</body>
</html>
like image 36
Yohan Liyanage Avatar answered Nov 16 '22 18:11

Yohan Liyanage