我有一些带有Servlets代码的JavaScript代码,我想将它们(之间)移动到外部js文件,但它不起作用,我该怎么办?如果只有部分JavaScript可以移动到外部文件,如何修改我的代码。
<script language="JavaScript" type="text/JavaScript">
var sel = document.getElementById('sel');
var selList = [];
<%
String key = "";
String text = "";
for(int i = 0; i < master.size(); i++) {
Map option = (Map) master.get(i);
key = (String) option.get("Code");
text = key + " " + (String) option.get("NAME");
%>
selList.push({
key: "<%=key%>",
text: "<%=text%>"
});
<%
}
%>
</script>
答案 0 :(得分:1)
这里有两个选项:
1 - 不使用ajax
external.js
var images;
function renderImages(){
//do things for showing images here.
//images variable has images data as JSON (i suggest you this way) so you can easily iterate over list and render it.
}
JSP
<html>
<head>
<script type="text/javascript" src="external.js"></script>
<script>
images = "<%=request.getAttribute("imageDataAsJSON")%>"; //here i assume you populate request variable with your image data in JSON format. Be careful about parse errors due to ' and ".
</script>
</head>
<body>
<script>
renderImages();
</script>
</body>
</html>
2 - 使用ajax (您可以将客户端逻辑分离到外部js代码中,并通过对服务器端执行ajax调用将数据填充到其中。)
external.js
function renderImages(){
//do ajax to your servlet which returns image data as JSON.
//iterate over image data and render your html elements accordingly.
}
JSP
<html>
<head>
<script type="text/javascript" src="external.js"></script>
</head>
<body>
</body>
</html>