【问题标题】:how to run javascript in html loaded via ajax如何在通过ajax加载的html中运行javascript
【发布时间】:2011-12-27 04:14:00
【问题描述】:

我有一个 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);  
}
}

例如,我将通过以下方式在 inxex.php 中加载一个文件:

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

这会将“contentpage.php”的内容粘贴到 div“updateThisDiv”中,但现在如果我在“contentpage.php”上有任何 javascript,它将无法运行,有什么办法吗?

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

我希望能够在不重新加载整个页面的情况下更新页面的一部分并且必须运行 javascript

【问题讨论】:

标签: php javascript html ajax xmlhttprequest


【解决方案1】:

如果您动态插入脚本标记,代码将执行。不要使用评估。图书馆知道这一点,他们也不使用 eval(除非他们很糟糕)。

【讨论】:

  • 我有 在我通过我的 ajax 脚本加载的 php 文件中,它不会打印出时间,就像我直接浏览到带有它的 php 页面一样
  • @JasonRussell Laith Shadeed 提供了 AutoSponge 建议的示例
【解决方案2】:

如果您想按需加载 Javascript。这可以通过动态创建脚本标签来完成。这种模式在 Stoyan Stefanov 书中说明 - Javascript Patterns

这是从书中摘录的:

编写一个需求函数。然后这样称呼它:

require("extra.js", function () {
    functionDefinedInExtraJS();
});

示例需要函数:

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中找到的实时示例

@Edit:针对您的案例的更多详细信息。我会尽量让事情变得简单:

创建四个文件:

  • index.php : 测试文件。
  • code.js : 具有 Ajax、getJS、getHTML 函数的实际代码
  • content.php : 任何 PHP 文件,无需任何 JS 即可打印纯 HTML
  • 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>

内容.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);
    }
}

【讨论】:

【解决方案3】:

这 100% 有效.....但我宁愿不使用 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?
  • 我宁愿拥有自己的方法或函数,我需要这样做: evalJS (Boolean | String; default true): 自动评估 Ajax.Response#responseText 的内容并使用如果服务器返回的 Content-type 设置为 application/json。如果请求不遵守同源策略,则在评估之前对内容进行清理。如果您需要强制评估,请通过“强制”。要完全防止它,请传递 false.api.prototypejs.org/ajax
猜你喜欢
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
  • 2013-11-24
  • 1970-01-01
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
相关资源
最近更新 更多