0

I have some JavaScript code with Servlets code, I want to move all of them (between ) to external js file, but it doesn't work, what can I do? How to modify my code if only part of JavaScript can move to external file.

<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>
6
  • Possible duplicate of Using JSP code in JavaScript Commented Jun 1, 2017 at 6:54
  • That doesn't answer how to use servlets ... Commented Jun 1, 2017 at 7:00
  • Then you need to be a little bit more specific. What are you trying to achieve. (Add that to your question) Commented Jun 1, 2017 at 7:07
  • I modified my question, can you help me? Commented Jun 1, 2017 at 7:14
  • As I understand you want to move Javascript that has some embedded JSP Java in it to a seperate .js file. That is exactly what the duplicate question is about... Commented Jun 1, 2017 at 7:15

1 Answer 1

1

Here two options:

1-by not using 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-by using ajax (you can seperate client side logic into external js code and populate data into it by doing ajax calls to server side.)

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I just want to show a image. Do I have to modify my logic if follow your way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.