如何运行JavaScript的HTML通过AJAX加载 [英] how to run javascript in html loaded via ajax

查看:114
本文介绍了如何运行JavaScript的HTML通过AJAX加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过这个JavaScript / AJAX code加载其他PHP文件的index.php文件:

I have an index.php file that loads other php files via this javascript/ajax code:

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:

so for example I would load a file in inxex.php by:

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

这将粘贴contentpage.php入格updateThisDiv的内容,但现在如果我有contentpage.php任何JavaScript,它不会运行,有没有办法做到这一点?

which would paste the contents of "contentpage.php" into the div "updateThisDiv" but now if I have any javascript on "contentpage.php", it will not run, is there any way to do this?

我已经看过这个: http://www.javascriptkit.com/script/ SCRIPT2 / ajaxpagefetcher.shtml 但它不是exatcly我所期待的。

I have looked at this: http://www.javascriptkit.com/script/script2/ajaxpagefetcher.shtml but its not exatcly what I was looking for.

我希望能够更新我的页面的部分,而不重新加载整个页面和JavaScript必须运行

I want to be able to update a section of my page without reloading the entire page and javascript must run

推荐答案

。这可以通过动态地创建脚本标签来完成。在斯托扬斯特凡本书图文并茂,这种模式 - 的 Javascript的模式

If you want to load Javascript on demand. This can be done by dynamically creating script tag. This pattern illustrated in Stoyan Stefanov book - Javascript Patterns

这从本书中摘录:

撰写要求的功能。然后调用它是这样的:

Write a require function. Then call it like this:

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

样品需要的功能:

Sample require function:

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

Live example found in http://www.jspatterns.com/book/8/ondemand.html

@Edit:更多细节具体到你的情况。我会努力让事情变得简单:

@ more details specific to your case. I will try to make things simple:

创建四肢文件:

  • 的index.php:测试文件
  • code.js:实际code具有阿贾克斯,getJS,getHTML功能
  • content.php:将打印纯HTML没有任何JS
  • 任何PHP文件
  • content.js:要动态地运行JavaScript code
  • index.php : the test file.
  • code.js : actual code which have Ajax, getJS, getHTML functions
  • content.php : any PHP file that will print pure HTML without any JS
  • content.js : javascript code that you want to run dynamically.

的index.php

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

content.php

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

content.js

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

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

这篇关于如何运行JavaScript的HTML通过AJAX加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆