How to call a JS function in a .js file into a .jsp file?

I am trying to call a javaScript function which in the file ... /js/index.js is in the file ... /index.jsp.

Any suggestion would be helpful.

Here is the code in both files:

index.js

function testing() { if ("c" + "a" + "t" === "cat") { document.writeln("Same"); } else { document.writeln("Not same"); }; }; 

index.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <script type="text/javascript" src="js/index.js"> <!-- I want to call testing(); function here --> </script> </body> </html> 
+6
source share
2 answers

First, access the external index.js file, and then call the function in the inline script element:

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> testing(); </script> </body> </html> 

By the way, you have an error in your function test.js. You must not set conditions ; after if / else, nor at the end of the function declaration. The correct syntax is:

 function testing() { if ("c" + "a" + "t" === "cat") { document.writeln("Same"); } else { document.writeln("Not same"); } } 

or

 var testing = function() { if ("c" + "a" + "t" === "cat") { document.writeln("Same"); } else { document.writeln("Not same"); } }; 
+18
source

You can do it

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <script type="text/javascript" src="js/index.js"></script> <title>Insert title here</title> </head> <body> <input type = "button" onclick = "javascript:testing()"/> </body> </html> 

This is the easiest

-1
source

Source: https://habr.com/ru/post/919935/


All Articles