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.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With