簡體   English   中英

如何在通過ajax加載的html中運行javascript

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

我有一個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

如果動態插入腳本標簽,則代碼將執行。 請勿使用評估。 圖書館知道這一點,他們也不使用eval(除非它們很糟糕)。

如果要按需加載Javascript。 這可以通過動態創建腳本標簽來完成。 Stoyan Stefanov-Javascript Patterns中說明了這種模式

這是從書中摘錄的:

編寫一個require函數。 然后這樣稱呼它:

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:針對您的情況的更多詳細信息。 我將嘗試使事情變得簡單:

創建fours文件:

  • index.php:測試文件。
  • code.js:具有Ajax,getJS,getHTML函數的實際代碼
  • content.php:任何將打印純HTML而沒有任何JS的PHP文件
  • 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);
    }
}

這有效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