Sending dynamically generated javascript file

Background:

I have a servlet in which I dynamically generate javascript and put in a variable script. Then I set the content type of the response as I text/javascriptsend the script to the client:

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

Problem:

The browser loads the javascript file, but does not recognize the functions inside the file. If I create a static javascript file and use it instead, it works fine.

Question:

What needs to be done for the browser to treat the servlet response as a regular javascript file?

Thank you for your help.

+5
source share
4 answers

. , .

:

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

@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'); }");
    }

}

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

+6

?

HTML- (), .

Ex.

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

, , Ajax, eval.

, , HTML. JS , script.

. , text/html:

<html>
<body>
 <script type='text/javascript'>
     <!-- write your generated JS here -->
 </script>
</body>
</html>
+1

script 'in-line' -.

0

, .

<%@ page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
alert('Pure JavaScript right here!');

JSP:

contentType="text/javascript; charset=UTF-8"
0

All Articles