English 中文(简体)
发送动态生成的javascript文件
原标题:Sending dynamically generated javascript file

背景:

我有一个servlet,我在其中动态生成javascript,并将其放入变量<code>脚本text/javascript,并将脚本发送到客户端:

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

问题:

浏览器确实下载了javascript文件,但无法识别文件中的函数。如果我创建一个静态javascript文件并使用它,它会很好地工作。

问题:

应该做些什么才能使浏览器将servlet的响应视为常规的javascript文件?

谢谢你的帮助。

最佳回答

它应该可以正常工作。我怀疑您只是以错误的方式包含它,或者过早调用函数,或者响应内容格式错误。

我刚刚做了一个快速测试:

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

}

我得到

问题回答

如何从浏览器中引用此servlet?

如果您想将其包含在HTML页面(现有页面)中,您应该从页面的标记中引用它。

Ex。

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

或者,如果您希望它作为Ajax调用的一部分执行,只需将响应传递给eval函数即可。

或者,如果您只想发送输出并在浏览器中执行,您还需要发送HTML段。然后将你的JS包含在body标记中,作为脚本标记。

例如,servlet使用内容类型text/html发送以下内容:

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

您可以随时在网页中直接编写脚本。

我觉得这样更好。

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

在JSP中设置内容类型:

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




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签