在ajax加载页面后执行javascript脚本 - 不起作用

Deu*_*ion 1 javascript php ajax google-maps

我正在尝试使用AJAX获取页面,但是当我获得该页面并且它包含Javascript代码时 - 它不会执行它.

为什么?

我的ajax页面中的简单代码:

<script type="text/javascript">
alert("Hello");
</script>
Run Code Online (Sandbox Code Playgroud)

......它没有执行它.我正在尝试使用Google Maps API并使用AJAX添加标记,因此每当我添加一个我执行获取新标记的AJAX页面时,将其存储在数据库中并应将"动态"标记添加到地图中.

但由于我无法以这种方式执行单个javascript函数,我该怎么办?

我在页面上定义的功能是预先保护还是私有?

**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();
}
Run Code Online (Sandbox Code Playgroud)

**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);

    }
}
Run Code Online (Sandbox Code Playgroud)

在某些事件中,我不得不在脚本addevent监听器中,而不是只是做一个"select onchange ='executeFunctionNotIncludedInAjaxFile();'"我必须为此添加事件监视器("更改","函数名称","假").在正在评估的脚本中.

Poi*_*nty 5

当您通过执行诸如将容器设置innerHTML为某些更新内容之类的操作来更新页面时,浏览器将无法在其中运行脚本.您可以找到<script>标签,获取它们innerHTML(IE可能更喜欢innerTEXT),然后eval()自己编写脚本(这几乎就是jQuery所做的,尽管在更新DOM之前它会找到带有正则表达式的脚本).