簡體   English   中英

是否可以根據窗口變量在 JSP 中有條件地加載腳本標簽?

[英]Is it possible to conditionally loading script tag in JSP based on window variable?

嗨,我必須根據窗口變量有條件地在我的一個 jsp 文件中加載腳本。 有人可以建議我如何實現這一點。 是否可以 ?

當前行為: 1. mytest.jsp 文件 2. 當前加載為

我想實現類似的東西

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

</c:if>

您需要將客戶端瀏覽器數據發送到服務器。 在“真”響應中,瀏覽器將加載額外的腳本。

這是后端服務的代碼: 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>

這將是 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM