0

Hi I have to conditionally load a script in one of my jsp files based on a window variable. Can someone suggest me how can i acheive this. Is it possible ?

Current behaviour : 1. mytest.jsp file 2. currently loading as

I wanted to acheive something like

<c:if **test="${window.loadScripts}**"> 
 <script type="text/javascript" src="myscript.js"></script>
 <script type="text/javascript" src="myscript2.js"></script>

</c:if>
Deadpool_er
  • 215
  • 4
  • 20
  • Does this answer your question? [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – VLAZ Jan 03 '20 at 21:45

1 Answers1

0

You need to send the client browser data to the server. On a "true" response the browser will load the additional scripts.

This is the code for the backend service: getjsvariables.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8");%>
<jsp:scriptlet>
    String test = request.getParameter("test");
    if(test.equals("x")) {
        out.print("doprint");
    } else {
        out.print("dontprint");
    }
</jsp:scriptlet>

This will be your code for the ajax call: getvariables.js

function postData(url, data, success) {
  // convert post data to string
  let i = 0;
  let post_data = "";
  for (const [key, value] of Object.entries(data)) {
    if (i > 0) {
      result += "&";
    }
    post_data += key + "=" + value;
    i++;
  }
  // ajax call
  let xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      success(this.responseText);
    }
  };
  xhttp.open("POST", url, true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(postData(postData));
}
let printYourScripts = function (response) {
    if(response == "doprint") {
        let html = '<script src="script1.js"></script>';
        html += '<script src="script2.js"></script>';
        document.body.innerHTML += html;
    }
}
let postData = {
    test: "x"
};
// RUN
let url = "getjsvariables.jsp";
postData(url, postData, printYoutScripts);