2011-06-07 40 views
0

我有index.html頁面。ajax。如何從請求的html文件調用javascript代碼

該網頁內我有JavaScript代碼,使一個按鈕來喚起對於other.html AJAX請求要顯示在的index.html一個div內部。

other.html除了div(包含內容)和一些javascript代碼外沒有別的。

other.html正常加載index.html但JavaScript代碼不起作用。

任何人都知道爲什麼會發生這種情況?

謝謝。 (JavaScript代碼與提醒(「hello」)消息一樣簡單)。

代碼:

的index.html:

<html> 
<head> 
<script src=main.js></script> 
</head> 

<body> 
<div id="to_change">bla bla bla</div> 
<div id="button">click me</div> 
</body> 
<html> 

main.js:

... 
... 
function sendRequest() 
{ 
    request.open("GET","other.html",true); 
    request.onreadystatechange = function(){ 
     if(request.readyState == 4 && request.status == 200){ 

      var response = request.responseText; 

      if(response) { 
       document.getElementById("to_change").innerHTML = response; 
      } 
     } 
    } 
    request.send(null); 
} 

....button.click(...sendRequest...); 
... 
... 

other.html

<script type=...>alert("hello");</script> 
<div>text text text text</div> 
+0

如何index.html的加載Ajax頁面,更重要的是,javascript是如何放置在other.html中的?你可以發佈你的代碼嗎? – Niklas 2011-06-07 15:56:26

+0

你真的應該提供你正在使用的代碼。如果您使用的是JQuery,則腳本標籤中的代碼將被刪除。最好將javascript放在你的'index.html'中。 – js1568 2011-06-07 15:56:27

+0

我編輯了一些簡單的代碼,因爲原稿太長。這有幫助嗎? – kostan 2011-06-07 16:16:15

回答

0

的JavaScript加載但函數調用不發生。

您在任何情況下都不會調用函數。

<BODY onLoad="alert('hello world!')"> 

像這樣嘗試調用函數。無論您想要什麼事件

+0

但我應該在哪裏寫這個事件?在index.html或其他的HTML?它似乎並不工作 – kostan 2011-06-07 17:17:00

0

確保從「other.html」文件中刪除封閉的「<doctype...>」,「<html>」和「<body>」標記,以防它們存在。

+0

是的,我已經刪除它們。但我認爲它沒有任何改變 – kostan 2011-06-07 17:26:49

0

你可以嘗試手動運行腳本:

// ... 
if (response) { 
    var toChange=document.getElementById("to_change"), scripts, i; 
    toChange.innerHTML = response; 
    scripts = toChange.getElementsByTagName('script'); 
    for (i=0; i<scripts.length; i++) { 
    eval(scripts[i].innerHTML); 
    } 
} 

當然,EVAL是,所以需要您自擔風險使用...