如何在JSP页面中将Java字符串传递给JavaScript函数 [英] How to pass a Java String to a JavaScript function in a JSP page

查看:112
本文介绍了如何在JSP页面中将Java字符串传递给JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将Java字符串传递给javascript showContent函数的方法. Java和javascript都包含在JSP页面中.字符串strLine包含我想使用showContent函数显示的XML内容.

I am looking to pass a string from my Java to a javascript showContent function. Both the Java and javascript are contained in a JSP page. The string strLine contains XML content I want to display using the showContent function.

我的Java

        try{    
        //Open the file that is the first command line parameter
            FileInputStream fstream = new FileInputStream(table.get(xmlMatch));                 

            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

        //Read File Line By Line
            while ((strLine = br.readLine()) != null)   
            {
                out.println (strLine);
            }  

Javascript(我必须感谢Peter在另一个

The Javascript (I have to credit Peter for supplying me with this in another question)

<script type="text/javascript" language="JavaScript">
function showContent()
{
document.getElementById('showContent').innerHTML = "printed content";
}
</script>

我尝试用"strLine"; (strLine);("strLine");

我还尝试使用以下方法将strLine设置为会话属性 session.setAttribute("strLine", strLine);并使用"<%=strLine%>";,但结果未显示在屏幕上.

I also tried set strLine as a session attribute using session.setAttribute("strLine", strLine); and using "<%=strLine%>"; but the result was null printed to the screen.

任何对此的帮助都会很棒.

Any help with this would be great.

HTML

<a href="#" onclick="showContent()">Next! <%=keywords%> concept </a>
<div id="showContent"></div>

推荐答案

而不是使用out.println打印,您应该放入一个变量(也许是StringBuilder).为此,您必须:

Instead of printing it with out.println, you should put in a variable (a StringBuilder maybe). In order to do that you have to:

在正确的范围内(也许在JSP的开头)声明变量

Declare the variable at the right scope (maybe at the beginning of the JSP)

StringBuilder contentInnerHtml = new StringBuilder();

然后将文件文本附加到此新变量:

Then append the text of the file to this new variable:

while ((strLine = br.readLine()) != null)   
{
    contentInnerHtml.append(strLine);
}

最后,在代码的javascript部分中返回其值(使用toString()):

Finally, in the javascript part of the code return its value (with toString()):

<script type="text/javascript" language="JavaScript">
function showContent()
{
    document.getElementById('showContent').innerHTML = "<%=contentInnerHtml.toString()%>";
}
</script>

这篇关于如何在JSP页面中将Java字符串传递给JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆