2015-08-27 90 views
2

我在使用Javascript的代碼中使用AJAX調用。使用Javascript解析HTML中的AJAX resposne

function loadFacility(callback) 
{ 
    //alert('In loadFacility'); 
    var xmlhttp; 
    var keys=document.firstCallInformation.facilityselect.value; 
    var urls="http://localhost:8080/webfdms/showFirstCallInformation.do?vitalsId=366"; 
    if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() 
    { 
     if (xmlhttp.readyState==4 && xmlhttp.status == 200) 
     { 
      //var some=xmlhttp.responseXML.documentElement; 
      var response = xmlhttp.responseText; 
      console.log(response) 
      callback(xmlhttp.responseText); 
     } 
    } 
    xmlhttp.open("GET",urls,true); 
    xmlhttp.send(null); 
} 
function loadFacilityCallback(response){ 
if(response != null){ 
    //alert(response); 
    console.log(response); 
    var div = document.createElement("div"); 
    div.innerHTML = response; 
    document.getElementById("facilityselect").innerHTML = div.querySelectorAll("select#facilityselect");; 
} 

編輯: 我已經更新了我的回調函數。但是在這裏,我收到了選擇列表作爲[Object Nodelist]。現在我怎樣才能在我的HTML中顯示?

在回調函數中,我現在收到了HTML的響應,我想解析該HTML響應,以便我可以進一步處理它。我使用普通的JavaScript來做到這一點。請任何人告訴我如何解析作爲HTML收到的Ajax響應。

回答

3

創建DIV元素,並把HTML中它innerHTML。這將解析它。

var div = document.createElement("div"); 
div.innerHTML = response; 

現在,您可以在div(例如, div.querySelector(".classname")。爲了讓所有的<select>標籤,這樣做:

var selects = div.querySelectorAll("select"); 

把它放入您的網頁,你可以這樣做:

document.getElementById("facilityselect").innerHTML = div.querySelector("select#facilityselect").innerHTML 
+0

基本上我想從解析的html中獲取選擇標記並將其顯示在頁面上。並有許多選擇標籤。所以我如何獲取它? –

+0

我更新了答案。 – Barmar

+0

我想從所有選擇標籤的列表中取出特定的選擇標籤? –

1

試試這個:

var dom='Your http response'; 
var wrapper=document.createElement('div'); 
wrapper.innerHTML=dom; 
var elemContainer=wrapper.firstChild; 
var elemToFind=elemContainer.querySelectorAll('option'); 
var facilityselect=document.getElementById('facilityselect'); 
facilityselect.innerHTML=''; 
for(var i=0, len=elemToFind.length; i < len; i++){ 
    facilityselect.appendChild(elemToFind[i]); 
} 

Creating a fake div element and appending your string which contains a HTML string will help. To insert a DOM object in specific selector, you need to user appendChild method.In case you want to empty the selector and then insert the DOM then set innerHTML as empty (selector.innerHTML="") and then do the append operation.

+0

基本上我想從解析的HTML獲取選擇標籤並顯示在頁面上。並有許多選擇標籤。所以我如何獲取它? –

+0

請檢查編輯... – Rayon

+0

請參閱我的編輯。我更新了回調函數,現在我正在獲取nodelist。現在的問題是如何更新我的HTML。 –