简体   繁体   English

如何在通过ajax加载的html中运行javascript

[英]how to run javascript in html loaded via ajax

I have an index.php file that loads other php files via this javascript/ajax code: 我有一个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);  
}
}

so for example I would load a file in inxex.php by: 因此,例如,我将通过以下方式在inxex.php中加载文件:

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

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? 这会将“ contentpage.php”的内容粘贴到div“ updateThisDiv”中,但是现在如果我在“ contentpage.php”上有任何JavaScript,它将无法运行,有什么办法吗?

I have looked at this: http://www.javascriptkit.com/script/script2/ajaxpagefetcher.shtml but its not exatcly what I was looking for. 我已经看过了: http : //www.javascriptkit.com/script/script2/ajaxpagefetcher.shtml,但这并不是我要找的东西。

I want to be able to update a section of my page without reloading the entire page and javascript must run 我希望能够更新页面的一部分而无需重新加载整个页面,并且必须运行javascript

If you dynamically insert a script tag the code will execute. 如果动态插入脚本标签,则代码将执行。 DO NOT USE EVAL. 请勿使用评估。 Libraries know this, they don't use eval either (unless they're terrible). 图书馆知道这一点,他们也不使用eval(除非它们很糟糕)。

If you want to load Javascript on demand. 如果要按需加载Javascript。 This can be done by dynamically creating script tag. 这可以通过动态创建脚本标签来完成。 This pattern illustrated in Stoyan Stefanov book - Javascript Patterns Stoyan Stefanov-Javascript Patterns中说明了这种模式

This snipped from the book: 这是从书中摘录的:

Write a require function. 编写一个require函数。 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);
}

Live example found in http://www.jspatterns.com/book/8/ondemand.html http://www.jspatterns.com/book/8/ondemand.html中找到的实时示例

@Edit: more details specific to your case. @Edit:针对您的情况的更多详细信息。 I will try to make things simple: 我将尝试使事情变得简单:

Create fours files: 创建fours文件:

  • index.php : the test file. index.php:测试文件。
  • code.js : actual code which have Ajax, getJS, getHTML functions code.js:具有Ajax,getJS,getHTML函数的实际代码
  • content.php : any PHP file that will print pure HTML without any JS content.php:任何将打印纯HTML而没有任何JS的PHP文件
  • content.js : javascript code that you want to run dynamically. content.js:要动态运行的javascript代码。

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

this works 100%.....but I would prefer to not use jquery 这有效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>

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

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