1

我的问题是:可以在 html 中插入 jsp 响应(html)吗?我认为使用 XmlHttpRequest。

xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML =
      this.responseText;
  }
};
xhttp.open("GET", "ajax_info.jsp", true);
xhttp.send();

我的问题是:但是如果我的jsp中有javascript在页面加载后执行,它是否像我直接通过浏览器url调用jsp一样执行?

提前致谢

例如:这是 index.html

<html>
<head>
<script type="text/javascript" src="app.js"></script>
</head>
<body onload="loadInfo();">

<div id="container"></div>
</body>

这是 app.js:

function loadInfo(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("container").innerHTML =this.responseText;
    }
  };
  xhttp.open("GET", "info.html", true);
  xhttp.send();
}

这是 info.html(我有 jsp,但我认为它是相同的..):

<html>
<head>
<script type="text/javascript" src="info.js"></script>
</head>
<body>
<div id="body_info">This is info..</div>
<script type="text/javascript" >
  console.log("wait for info..");
  info();
</script>
</body>

这是 info.js:

function info(){

    document.getElementById("body_info").innerHTML ="info.js is executed";
}

如果我调用 info.html,在浏览器中输入 url(例如http://localhost:8000/info.html),脚本被执行并且我得到“info.js 被执行”,而不是如果我调用 index.html,也许xhr 请求返回不一样,但我看到“这是信息”。

我如何使用 xhr 解决和完成这个问题?

谢谢
罗伯托

4

1 回答 1

0

当您将 ajax 调用到某个页面时,那么下面的内容<body></body>将作为响应返回,因此您的代码中this.responseText也将包含<script></script>代码。您可以检查您是否正在使用 chrome,然后单击element tab您会看到<script></script>哪个返回为response.Now,要执行此操作,您可以执行以下操作:

function loadInfo() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("container").innerHTML = this.responseText;
      //getting the script which is return as response back 
      var datas = document.getElementById("container").getElementsByTagName("script");
      //looping  unders <script></script>
      for (var i = 0; i < datas.length; i++) {
        console.log("inside script executing")
        eval(datas[i].innerText); //executing script
      }
    }
  };
  xhttp.open("GET", "n.html", true);
  xhttp.send();
}

您的脚本info.html如下所示:

<script>
console.log("wait for info..");
info();

function info() {
 document.getElementById("body_info").innerHTML = "info.js is executed";
}
</script>
于 2020-05-24T12:11:05.877 回答