2011-07-24 31 views
0

我在互聯網上發現了這段代碼,它似乎在工作,但無論我命名將加載到DIV中的文件總是得到相同的消息「沒有找到對象」我該怎麼做才能讓文件加載?替換DIV內容Javascript,無法獲得外部文件名的權利

這是HTML代碼...

<a href="javascript:void()" onclick="javascript:sendRequest('sourcepage?id=34', 'targetdiv')">Link Text</a> 
<div id="targetdiv">This is the target</div> 

所以......我有什麼命名爲 「sourcepage?ID = 34」 的文件,以獲得它的權利?到目前爲止,我已經嘗試過「id34.html」,「sourcepage-34.html」和類似的東西,但似乎沒有工作。

腳本:

function createRequestObject() 
{ 
    var returnObj = false; 

    if(window.XMLHttpRequest) { 
     returnObj = new XMLHttpRequest(); 
    } else if(window.ActiveXObject) { 
     try { 
      returnObj = new ActiveXObject("Msxml2.XMLHTTP"); 

      } catch (e) { 
      try { 
      returnObj = new ActiveXObject("Microsoft.XMLHTTP"); 
      } 
      catch (e) {} 
      } 

    } 
    return returnObj; 
} 

var http = createRequestObject(); 
var target; 

// This is the function to call, give it the script file you want to run and 
// the div you want it to output to. 

function sendRequest(scriptFile, targetElement) 
{ 
    target = targetElement; 
    try{ 
    http.open('get', scriptFile, true); 
    } 
    catch (e){ 
    document.getElementById(target).innerHTML = e; 
    return; 
    } 
    http.onreadystatechange = handleResponse; 
    http.send();  
} 

function handleResponse() 
{ 
    if(http.readyState == 4) {  
    try{ 
     var strResponse = http.responseText; 
     document.getElementById(target).innerHTML = strResponse; 
     } catch (e){ 
     document.getElementById(target).innerHTML = e; 
     } 
    } 
} 

我覺得這是最愚蠢的問題,我已經在我的生活做了對不起......對於與在此先感謝:d

+0

你想加載到div中? – marc

+0

很難判斷它是哪一個,但是你的代碼中的一些'Object'是'undefined'。你需要找出它是哪一個。爲了做到這一點,你必須在你的代碼中添加一些行,告訴你在哪裏引發'Error',或者只是使用安裝了Firebug的Firefox。 – FK82

+0

我想加載一個外部HTML,然後將其加載到帶有鏈接的DIV中...並且Firebug不會給我任何錯誤。 – Liuny

回答

0

好文件名你正在嘗試使用沒有擴展名。根據其他服務器的配置,可以重新路由到多種不同的文件類型。 「?id = 34」是url參數,與文件名無關。只需更換文件名:

<a href="javascript:void()" onclick="javascript:sendRequest('myFile.html', 'targetdiv')">Link Text</a> 
<div id="targetdiv">This is the target</div> 

並命名文件myFile.html並將其放置在同一個文件夾,其中上面的HTML是。如果使用jQuery是你的選擇,我會推薦它,你可以做你想要的:

$('#targetdiv').load('myFile.html', function(){ 
    // code to execute once the HTML is loaded into your div 
});