我的问题是:可以在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时那样执行吗?
提前感谢
例如: This is 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 is executed",相反,如果我调用index.html,也许xhr请求不会返回相同的信息,但我会看到"This is info“。
如何使用xhr解决和完成此问题?
谢谢
罗伯托
发布于 2020-05-24 20:11:06
当您对某个页面进行ajax调用时,<body></body>下的任何内容都将作为响应返回,因此在您的代码中,this.responseText中也将包含<script></script>代码。你可以检查你是否正在使用chrome,然后点击element tab,你也会看到<script></script>,这是return as 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>https://stackoverflow.com/questions/61972341
复制相似问题