简体   繁体   English

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

[英]Executing javascript script after ajax-loaded a page - doesn't work

I'm trying to get a page with AJAX, but when I get that page and it includes Javascript code - it doesn't execute it. 我正在尝试使用AJAX创建一个页面,但是当我获得该页面并且其中包含Javascript代码时,它不会执行。

Why? 为什么?

Simple code in my ajax page: 我的ajax页面中的简单代码:

<script type="text/javascript">
alert("Hello");
</script>

...and it doesn't execute it. ...并且它不执行它。 I'm trying to use Google Maps API and add markers with AJAX, so whenever I add one I execute a AJAX page that gets the new marker, stores it in a database and should add the marker "dynamically" to the map. 我正在尝试使用Google Maps API并使用AJAX添加标记,因此,每添加一个标记,我都会执行一个AJAX页面,该页面将获取新标记,并将其存储在数据库中,并应将标记“动态”添加到地图中。

But since I can't execute a single javascript function this way, what do I do? 但是,由于我无法以这种方式执行单个javascript函数,该怎么办?

Is my functions that I've defined on the page beforehand protected or private? 我在页面上预先定义的功能是受保护的还是私有的?

** UPDATED WITH AJAX FUNCTION ** **使用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();
}

** Solution by Deukalion ** ** 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);

    }
}

and on certain events, I had to within the script addevent listeners instead of just making a "select onchange='executeFunctionNotIncludedInAjaxFile();'" I had to addEventListener("change", functionName, false) for this. 在某些事件上,我不得不在脚本中添加事件侦听器,而不是仅仅为此创建一个“ select onchange ='executeFunctionNotIncludedInAjaxFile();'“。我必须为此添加addEventListener(” change“,functionName,false)。 In the script that is being evaluated. 在正在评估的脚本中。

When you update your page by doing something like setting a container's innerHTML to some updated content, the browser simply will not run the scripts in it. 当您通过执行将容器的innerHTML设置为某些更新内容之类的操作来更新页面时,浏览器根本不会在其中运行脚本。 You can locate the <script> tags, get their innerHTML (IE may prefer innerTEXT ), and then eval() the scripts yourself (which is pretty much what jQuery does, though it finds the scripts with a regex before updating the DOM). 您可以找到<script>标记,获取它们的innerHTML (IE可能更喜欢innerTEXT ),然后自己编写脚本eval() (这与jQuery innerTEXT ,尽管jQuery在更新DOM之前使用了正则表达式来找到脚本)。

Use this function: 使用此功能:

function parseScript(_source) {
    var source = _source;
    var scripts = new Array();

    // Strip out tags
    while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
        var s = source.indexOf("<script");
        var s_e = source.indexOf(">", s);
        var e = source.indexOf("</script", s);
        var e_e = source.indexOf(">", e);

        // Add to scripts array
        scripts.push(source.substring(s_e+1, e));
        // Strip from source
        source = source.substring(0, s) + source.substring(e_e+1);
    }

    // Loop through every script collected and eval it
    for(var i=0; i<scripts.length; i++) {
        try {
            eval(scripts[i]);
        }
        catch(ex) {
            // do what you want here when a script fails
        }
    }

    // Return the cleaned source
    return source;
}

then do parseScript(xmlhttp.responseText); 然后做parseScript(xmlhttp.responseText); when you're replacing/adding content. 当您替换/添加内容时。

In case some other people stumble upon this old thread, there is one issue with the accepted answer by Deukalion, there is one issue that may have been overlooked: as written, the script only looks for the first script tag. 如果其他人偶然发现了这个旧线程,那么Deukalion会接受一个问题,那就是一个可能被忽略的问题:如所写,脚本只寻找第一个脚本标签。 If multiple script tags exist, all others are overlooked. 如果存在多个脚本标签,则将忽略所有其他脚本标签。

A few minor tweaks would resolve the issue. 进行一些小的调整即可解决此问题。 Change one line from: 更改以下一行:

    var script = content.match("<script[^>]*>[^<]*</script>");

To: 至:

    var script = content.match(/<script[^>]*>[^<]*<\/script>/g);

And another from: 另一个来自:

    script = script.toString().replace('<script type="text/javascript">', '');

To: 至:

    script = script.join("").replace(/<script type="text\/javascript">/g, '');

Now it will gather all the <script> code and execute them in the order found on the page. 现在,它将收集所有<script>代码并按照页面上的顺序执行它们。 Otherwise it was an excellent solution. 否则,这是一个极好的解决方案。

After the AJAX request, you can make an "on success" function which can take the returned html and do something with it. 在AJAX请求之后,您可以创建一个“成功”函数,该函数可以接收返回的html并对其进行处理。 Then something will be executed. 然后将执行一些操作。

If there was a code example, then I could provide a code solution to the situation. 如果有代码示例,那么我可以为这种情况提供代码解决方案。 But using just standard xmlhttprequest, the following could be done: 但是仅使用标准的xmlhttprequest,可以完成以下操作:

xhr = new XMLHttpRequest();
xhr.open("GET","ajax_info.txt",true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
  {
  document.getElementById("myDiv").innerHTML = xhr.responseText;
  }
}
xhr.send();
​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM