如何在通过Ajax加载的HTML中运行JavaScript

3
我有一个index.php文件,通过以下javascript/ajax代码加载其他php文件:
function AJAX(elementID,url,showStatus){
var httpObject;
if (window.ActiveXObject) {
    httpObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (window.XMLHttpRequest){
    httpObject =  new XMLHttpRequest();
}
else {
    alert("Your browser does not support AJAX.");       
}

if (httpObject != null) {
    httpObject.onreadystatechange = function() {          
        if (elementID != false){                

            if (httpObject.readyState == 4 && httpObject.status == 200) {                  
                document.getElementById(elementID).innerHTML= httpObject.responseText;  

            } 
        }

    }

    httpObject.open("POST",url,true);
    httpObject.send(null);  
}
}

举个例子,我可以通过以下方式在index.php中加载一个文件:

<script>
AJAX("updateThisDiv", "/includes/contentpage.php", false)
</script>

如何将“contentpage.php”的内容粘贴到“updateThisDiv”中,但现在如果我在“contentpage.php”上有任何javascript,它将无法运行,是否有任何方法可以解决这个问题?

我已经看过了这个:http://www.javascriptkit.com/script/script2/ajaxpagefetcher.shtml,但这并不是我想要的。

我希望能够更新页面的某个部分而无需重新加载整个页面,并且javascript必须运行。


我找到了这个链接:http://stackoverflow.com/questions/4335142/why-would-php-generated-javascript-not-work-in-file-loaded-via-ajax 但不确定它是什么或如何使用它来获得我想要的结果。 - Jason Russell
看看这个是否有帮助:http://stackoverflow.com/questions/4775444/can-xmlhttp-responsetext-contain-script-type-text-javascript-src-scrip - david
如果您想查看我的问题示例,请访问http://russell.selfip.net/test - Jason Russell
你可以使用JavaScript通过AJAX调用获取新div的内容并更新它,我看不出有什么问题。 - RHT
eval函数可以实现,但是我现在无法看到原始HTML的任何内容,需要使用JavaScript打印输出。 - Jason Russell
@RHT 我正在获取新div的内容,其中包含JavaScript代码,我希望在获取时运行它。 - Jason Russell
3个回答

4
如果您想按需加载Javascript。这可以通过动态创建脚本标签来实现。该模式在Stoyan Stefanov的书中有所阐述 - Javascript Patterns 以下是书中的代码片段:
编写一个require函数。然后像这样调用它:
require("extra.js", function () {
    functionDefinedInExtraJS();
});

示例 require 函数:

function require(file, callback) {

    var script = document.getElementsByTagName('script')[0],
        newjs = document.createElement('script');

    // IE
    newjs.onreadystatechange = function () {
        if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
            callback();
        }
    };

    // others
    newjs.onload = function () {
        callback();
    };
    
    newjs.src = file;
    script.parentNode.insertBefore(newjs, script);
}

http://www.jspatterns.com/book/8/ondemand.html中找到实时示例

@编辑:更多与您情况相关的细节。我将尝试让事情变得简单:

创建四个文件:

  • index.php:测试文件。
  • code.js:实际代码,其中包括Ajax、getJS、getHTML函数
  • content.php:任何PHP文件,将打印纯HTML而没有JS
  • content.js:您想要动态运行的javascript代码。

index.php

<html>
    <head>
        <script src="code.js"></script>
    </head>
    <body>
        <input type="button" onclick="Ajax('content.php', 'd_html');" value="Fill from content.php"/>
        <div id="d_html"></div>
        <br>
        <input type="button" onclick="Ajax('content.js', 'd_js');" value="Fill from content.js"/>
        <div id="d_js"></div>
    </body>
</html>

content.php

<span>Hello, I am dynamic span came from content.php</span>

content.js

//Ana javascript code you want to run it by Ajax function should go inside this function
function executeJS(element){
   element.innerHTML = "<span>Hello, I am dynamic span came from content.js</span>";
}

code.js

//This function responsible for doing the ajax request for any file that will return pure HTML.
function getHTML(url, element){
    var i, xhr, activeXids = [
        'MSXML2.XMLHTTP.3.0',
        'MSXML2.XMLHTTP',
        'Microsoft.XMLHTTP'
    ];

    if (typeof XMLHttpRequest === "function") { // native XHR
        xhr =  new XMLHttpRequest();        
    } else { // IE before 7
        for (i = 0; i < activeXids.length; i += 1) {
            try {
                xhr = new ActiveXObject(activeXids[i]);
                break;
            } catch (e) {}
        }
    }

    xhr.onreadystatechange = function () {
        if (xhr.readyState !== 4) {
            return false;
        }
        if (xhr.status !== 200) {
            alert("Error, status code: " + xhr.status);
            return false;
        }
        
        element.innerHTML += xhr.responseText;
    };

    xhr.open("GET", url, true); 
    xhr.send("");
}

//This function will load javascript file on-demand and call executeJS function inside that file.
function getJS(url, element, cb){
    var newjs = document.createElement('script');
    
    // IE
    newjs.onreadystatechange = function () {
        if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
            cb();
        }
    };

    // others
    newjs.onload = function () {
        cb();
    };
    
    newjs.src = url;
    element.appendChild(newjs);
}


//This is same as your function, but now can handle both PHP and JS files
function Ajax(url, id){
    var element = document.getElementById(id),
        regex = /\.js$/;
    if(!element){
        alert("Invalid ID");
        return false;
    }

    if(regex.test(url)){ //If url ends with JS, load using getJS
        getJS(url, element, function(){
            executeJS(element);
        });
    } else {
        getHTML(url, element);
    }
}

我不太理解它,也不知道如何使用,但我会尝试。 - Jason Russell
好的,我会在你的测试文件http://russell.selfip.net/test/index.php中添加更多的描述来实现它。 - Laith Shadeed

2
如果您动态插入脚本标签,代码将会执行。请勿使用 EVAL。库知道这一点,它们也不使用 EVAL(除非它们很糟糕)。

1
我在通过我的ajax脚本加载的php文件中有<script type="text/javascript">var d=new Date(); document.write(d);</script>,但它不会像直接浏览带有此内容的php页面时那样打印出时间。 - Jason Russell
@JasonRussell Laith Shadeed 提供了一个例子,展示了AutoSponge的建议。 - david
将渲染到DOM,查询脚本,创建新脚本,然后将其附加到头部。请参见https://dev59.com/B0vSa4cB1Zd3GeqPf6F9#25406725。 - Justin

1

这个方法百分之百有效......但我宁愿不使用jQuery

<!DOCTYPE html>
<html dir=”ltr” lang=”en-US”>
<head>
    <meta charset=”UTF-8” />
    <title>AJAX Detection And Data Loading Using New School jQuery & HTML5:</title>            
    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js” 
type=”text/javascript”></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("button").click(function () {
                $("#mm").load("test.php");
            });
        });
    </script>
</head>
<body>
    <button type=”button”>Load Some Copy!</button>
    <div id="mm">
    </div>
    <section>
    </section>
</body>
</html>

除了使用jQuery,你更喜欢使用什么? - user212218
我宁愿拥有自己的方法或函数,我需要这样做:evalJS(布尔值|字符串;默认为true):如果服务器返回的Content-type设置为application/json,则自动评估Ajax.Response#responseText的内容并用其填充Ajax.Response#responseJSON。 如果请求不遵守同源策略,则在评估之前对内容进行清理。 如果您需要强制评估,请传递'force'。 要完全防止它,请传递false。http://api.prototypejs.org/ajax/ - Jason Russell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接