【问题标题】:call script tag by using ajax [duplicate]使用ajax调用脚本标签[重复]
【发布时间】:2017-01-18 06:29:39
【问题描述】:

例如,我正在尝试使用 ajax 调用脚本警报

我创建了两个文件 test1.php 和 test2.php

这是我的代码:

test1.php

更改内容

让 AJAX 改变这个文本

<script>

<pre><script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "test2.php", true);
xhttp.send();
}
</script>


</pre>
</script>

test2.php

<pre>
<script>alert('hello');</script>

echo "Hello User";
</pre>

问题是我的脚本标签没有被 ajax 调用并且显示空白响应。 请需要你的帮助。 再次感谢您。

【问题讨论】:

  • @JaromandaX 检查重复,由 innerHTML 制作的脚本标签预计不会运行。
  • 是的,对于重复的脚本标签很抱歉,但问题仍然存在,我无法从 test2.php 调用脚本警报
  • 为什么要在脚本周围加上&lt;pre&gt;?不渲染脚本,因此格式无关紧要。
  • 你会用jQuery吗?当您使用.html() 插入脚本时,它将执行脚本。

标签: javascript php ajax


【解决方案1】:

很容易,从 test2.php 中删除 &lt;script&gt;&lt;/script&gt;,然后在 test1.php 中更改:

document.getElementById("demo").innerHTML = this.responseText;

eval(this.responseText);

这里是完整的示例代码:

test1.php:

<html>
<body>
<script>
function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            eval(this.responseText);
        }
    };

    xhttp.open("GET", "test2.php", true);
    xhttp.send();
}

loadDoc();
</script>
</body>
</html>

和test2.php:

alert('hello');

【讨论】:

  • 感谢您的回复,但我仍然没有收到来自 test2.php 的 javascript 警报。如果可能的话,你能给我提供类似的工作示例吗?
  • 在你的 javascript 中你必须在创建它之后调用 loadDoc() 函数。
  • 非常感谢,它对我有用。我的另一个问题是我可以从 test2.php 中同时获取 javascipt alert 和 php echo statment 例如: alert('hello user');和 php echo "username : sam" ?> 像这样。再次感谢您的帮助
  • 有可能。有很多方法可以做到这一点。但其中之一是在 test2.php 脚本中创建您的 html 和文本数据。例如,您可以在警报脚本之前使用:document.write("hello user");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
  • 1970-01-01
  • 2020-05-10
  • 2022-01-14
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
相关资源
最近更新 更多