[英]Is it possible to conditionally loading script tag in JSP based on window variable?
Hi I have to conditionally load a script in one of my jsp files based on a window variable.嗨,我必须根据窗口变量有条件地在我的一个 jsp 文件中加载脚本。 Can someone suggest me how can i acheive this.有人可以建议我如何实现这一点。 Is it possible ?是否可以 ?
Current behaviour : 1. mytest.jsp file 2. currently loading as当前行为: 1. mytest.jsp 文件 2. 当前加载为
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>
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这是后端服务的代码: 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这将是 ajax 调用的代码: 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.