我正在尝试使用 AJAX 获取页面,但是当我获取该页面并且它包含 Javascript 代码时 - 它不会执行它。
为什么?
我的 ajax 页面中的简单代码:
<script type="text/javascript">
alert("Hello");
</script>
...它不会执行它。我正在尝试使用 Google Maps API 并使用 AJAX 添加标记,因此每当我添加标记时,我都会执行一个获取新标记的 AJAX 页面,将其存储在数据库中,并应“动态”将标记添加到 map 。
但由于我不能以这种方式执行单个 javascript 函数,我该怎么办?
我事先在页面上定义的函数是 protected 还是私有(private)的?
** 更新了 AJAX 功能 **
function ajaxExecute(id, link, query)
{
if (query != null)
{
query = query.replace("amp;", "");
}
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (id != null)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
}
if (query == null)
{
xmlhttp.open("GET",link,true);
}
else
{
if (query.substr(0, 1) != "?")
{
xmlhttp.open("GET",link+"?"+query,true);
}
else
{
xmlhttp.open("GET",link+query,true);
}
}
xmlhttp.send();
}
** Deukalion 的解决方案 **
var content = xmlhttp.responseText;
if (id != null)
{
document.getElementById(id).innerHTML=content;
var script = content.match("<script[^>]*>[^<]*</script>");
if (script != null)
{
script = script.toString().replace('<script type="text/javascript">', '');
script = script.replace('</script>', '');
eval(script);
}
}
并且在某些事件中,我必须在脚本中添加事件监听器,而不仅仅是制作“select onchange='executeFunctionNotIncludedInAjaxFile();'”我必须为此添加 addEventListener(“change”, functionName, false)。在正在评估的脚本中。
最佳答案
当您通过设置容器的 innerHTML
来更新您的页面时对于一些更新的内容,浏览器根本不会运行其中的脚本。您可以找到 <script>
标签,得到他们的 innerHTML
(IE 可能更喜欢 innerTEXT
),然后是 eval()
自己编写脚本(这几乎就是 jQuery 所做的,尽管它会在更新 DOM 之前使用正则表达式找到脚本)。
关于php - 在 ajax 加载页面后执行 javascript 脚本 - 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10888326/