2012-03-15 100 views
1

我正在使用下面介紹的Ajax和代碼。我想在Ajax XMLHttpRequest中包含.js文件。有誰知道如何做到這一點?在Ajax中包含js文件XMLHttpRequest

例如: 我有下面的代碼:

function getXMLHttp() 
{ 
    var xmlHttp 

    try 
    { 
    //Firefox, Opera 8.0+, Safari 
    xmlHttp = new XMLHttpRequest(); 
    } 
    catch(e) 
    { 
    //Internet Explorer 
    try 
    { 
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 
    } 
    catch(e) 
    { 
     try 
     { 
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     catch(e) 
     { 
     alert("Your browser does not support AJAX!") 
     return false; 
     } 
    } 
    } 
    return xmlHttp; 
} 

function MakeRequest(id) 
{ 
    var xmlHttp = getXMLHttp(); 

    xmlHttp.onreadystatechange = function() 
    { 
    if(xmlHttp.readyState == 4) 
    { 
     HandleResponse(xmlHttp.responseText); 
    } 
    } 

    xmlHttp.open("GET", "updatesite.admin.php?id="+id, true); 
    xmlHttp.send(null); 
} 

function HandleResponse(response) 
{ 
    document.getElementById('Vsebina').innerHTML = response; 
} 

當程序調用函數makeRequest的(ID),那麼我想也執行一些.js文件。 可以這樣做嗎?

+0

通過你的意思是「我想使用'innerHTML'將JS添加到頁面並讓它執行」? XMLHttpRequest似乎是一個紅鯡魚的東西。 – Quentin 2012-03-15 17:48:02

回答

1

你總是可以把這段代碼在你的函數導致腳本加載和執行...

var script = document.createElement("script"); 
script.type = "text/javascript"; 
script.src = "http://location-of-script.js"; 
document.body.appendChild(script); 

這裏有一個完整的例子。這兩個文件只需要在服務器上的同一個文件夾中。

這是hello.html的:

<html> 
<head> 
<script type="text/javascript"> 
function doit() 
{ 
    var scr = document.createElement('script'); 
    scr.type = "text/javascript"; 
    scr.src = "hello.js"; 
    document.body.appendChild(scr); 
} 
</script> 
</head> 
<body> 
<input type="button" value="hello" onclick="doit();"> 
</body> 
</html> 

這是hello.js: 「我想包括在名爲.js阿賈克斯XMLHttpRequest的文件」

alert("helloooo!!"); 
+0

感謝您的回答,但這沒有幫助。 – 2012-03-15 20:32:49

+0

真的嗎?我使用了很多。 – dldnh 2012-03-15 22:31:54

+0

是的,在一個更完整的例子中進行了測試,以確保我沒有在地板上掉落任何東西。 – dldnh 2012-03-15 22:50:21