我使用servlet在谷歌浏览器中工作我有以下代码:
public void process(String input, PrintWriter out)
{
System.out.println(input.indexOf("\\\\"));
String Json[]= input.split("\\\\");
for(int x =0; x< Json.length;x++)
{
System.out.println(Json.length);
//JSONProcess(json[x]);
out.println("<p class=\"json\" style =\"display:none\"> ");
out.println(Json[x]);
out.println("</p>");
}
out.println("<script>"+
"var JSONProcess= function(){\n" +
"var JsonInfo = document.getElementByClassName(\"json\");\n" +
"var canvasEl = document.getElementById(\"c\");\n" +
"var nodesData =[];\n"+
"window.alert(\"This is a test\");\n" +
"console.log(JsonInfo.length);\n"+
"for(var i = 0;i<JsonInfo.length; i++)\n" +
"{\n" +
"var Json = JsonInfo[x].innerHTML;\n" +
"if(Json.source == null)\n" +
"{\n" +
"nodesData.push([Json.x, Json.y, Json.r, Json.id]);\n" +
"}\n" +
"}\n" +
"for(var i=0; i<nodesData.length; i++)\n" +
"{\n" +
" var data = nodesData[i];\n" +
" console.log(data[1]);\n" +
" console.log(data[2]);\n" +
" console.log(data[3]);\n" +
"}\n" +
"}</script>");
}
虽然脚本标记不会引发任何错误,但是console.log或警报都不起作用。我试过了
删除window.log
这是作为对此问题的先前提问的答案,但没有做任何事情。控制台正在打印日志(我点击漏斗的东西来检查),我已关闭并重新打开铬。在这个问题的其他版本中提供的所有答案都没有奏效。
答案 0 :(得分:2)
您必须调用该函数
out.println("<script>"+
"var JSONProcess= function(){\n" +
"var JsonInfo = document.getElementByClassName(\"json\");\n" +
"var canvasEl = document.getElementById(\"c\");\n" +
"var nodesData =[];\n"+
"window.alert(\"This is a test\");\n" +
"console.log(JsonInfo.length);\n"+
"for(var i = 0;i<JsonInfo.length; i++)\n" +
"{\n" +
"var Json = JsonInfo[x].innerHTML;\n" +
"if(Json.source == null)\n" +
"{\n" +
"nodesData.push([Json.x, Json.y, Json.r, Json.id]);\n" +
"}\n" +
"}\n" +
"for(var i=0; i<nodesData.length; i++)\n" +
"{\n" +
" var data = nodesData[i];\n" +
" console.log(data[1]);\n" +
" console.log(data[2]);\n" +
" console.log(data[3]);\n" +
"}\n" +
"}" +
"JSONProcess()" + // here
"</script>");
请注意,打印这样的javascript并不是一个好习惯,你最好将javascript放在.js文件中,而只打印带有源代码的单个脚本标记。