2011-07-12 45 views
3

因此,我編寫了一些JavaScript來從我的桌面抓取xml文件並將其顯示在html頁面上。但是,我現在已經將我的xml文件添加到web服務器(mongoose)。我想從該服務器調用該文件,但每當我從服務器調用該文件時都不起作用,但是當我從桌面調用該文件時,它會正常加載。使用Javascript從服務器獲取文件

我想交換

xmlhttp.open("GET","Devices.xml",false); 

xmlhttp.open("GET","http://localhost:8080/Devices.xml",false); 

下面是代碼

<html> 
<head> 

<script type="text/javascript"> 
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
    else {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    xmlhttp.open("GET","Devices.xml",false); 
    xmlhttp.send(); 
    xmlDoc=xmlhttp.responseXML; 


    // the <Device> list 
    x = xmlDoc.getElementsByTagName('Device'); 

    // make a function that extracts the attributes out of a Node 
    function getDeviceAttributes(dvc) { 
    var name = dvc.getAttribute("name"); 
    var uuid = dvc.getAttribute("uuid"); 
    var id = dvc.getAttribute("id"); 
    return "<p>name: " + name + "<br> uuid: " + uuid + "<br> id: "+ id + "</p>"; 
    } 

    // loop through the list 
    // assuming order doesn’t matter 
    var txt = ''; 
    for (var i = x.length; i--;) { 
    txt += getDeviceAttributes(x[i]); 
    } 

    //show the result on page load 
    window.onload = function() { 
    document.getElementById("showDevices").innerHTML = txt; 
    }; 

</script> 
</head> 

<body> 

<div id='showDevices'></div> 

</body> 
</html> 

有誰知道我能得到這個工作?

我被告知使用AJAX和JQuery,但我不知道如何甚至從何處開始。

+6

您是否正在服務從同一個Web服務器獲取該文件的頁面?如果不是,你可能會遇到一些相同的原產地問題 –

回答

4

它看起來像你正在重複jQuery可以爲你做的很多工作。檢查出的文檔的Get request method

因此,像這樣:

$.get('http://localhost:8080/Devices.xml', function(data) { 
    $('#showDevices').html(data); 
}); 

我相信這是jQuery的什麼你正在嘗試做的。希望有所幫助。

-Charlie

只是一些通用的建議,你也可以使用.load()函數阿賈克斯如果不想解析響應和這樣的:

window.onload = function() { 
    document.getElementById("showDevices").innerHTML = txt; 
}; 

可以完成像這樣的jQuery $("#showDevices").html(txt);

相關問題