2014-07-22 70 views
0

當通過存儲在內部服務器上的網絡加載網站時,我遇到性能問題。性能問題歸結於我的Javascript文件中發出的多個AJAX請求,這些請求經常嘗試訪問XML文件,然後從XML節點或XML節點獲取圖像。合併Javascript AJAX請求

有沒有一種方法可以將AJAX請求合併在一起,以減少從客戶端設備到存儲在服務器上的XML文件的請求數量。

我的代碼如下:

function getimage(getID,XMLImageID) 
{ 
$("#" + getID).empty(); 
$.ajax({ 
type: "GET", 
url: "XML/XML.xml", 
dataType: "xml", 
success: function(xml){ 
$(xml).find(XMLImageID).each(function(){ 

var image = $(this).find("image[href]").attr("href"); 
$('#'+ getID).append($("<img"+" class="+"Timages"+" src=\"" +image+"\"/>")); 
});   
}, 
error: function() { 
alert("(getImage) An error occurred while processing XML file. Reasons could be: \n The XML cant be located. \n The XML is being used by another program. \n The XML is trying to parse incompatible characters. \n The XML syntax/tags are incorrect."); 
} 
}); 
} 

function getdept(getid,XMLID) 
{ 
var scriptTag = document.scripts[document.scripts.length - 1]; 
var parentTag = scriptTag.parentNode; 
getid = parentTag.id; 
$.ajax({ 
type: "GET", 
url: "XML/XML.xml", 
dataType: "xml", 
success: function(xml){ 
$(xml).find(XMLID).each(function(){ 
var dept = $(this).find('Dept').text();    
var id = $(this).attr("id"); 
var sName = $(this).find('Name').text(); 
$("#"+getid).append('<div class="Team_People" onmouseover="area_hover1(this);area_hover2(this)" href="#p'+id+'">'+dept+'<br />'+sName+'</div>'); 

}); 
}, 
error: function() { 
alert("(getHierPeopleDept)An error occurred while processing XML file. Reasons could be: \n The XML cant be located. \n The XML is being used by another program. \n The XML is trying to parse incompatible characters. \n The XML syntax/tags are incorrect."); 
} 
}); 
} 

Ajax響應使用下面的簡化代碼,我只需要合併上面的代碼,使之更加整潔,而非使用多個Ajax請求。不知道這是否可能(是否添加多個參數)?

$.ajax({ 
type: "GET", 
url: "XML/XML.xml", 
dataType: "xml", 
success: function(xml){ 
$(xml).find(XMLID).each(function(){ 
//Get something from XML node 
}); 
}, 
}); 
} 

如果任何人都可以引導我在正確的方向,將不勝感激! 感謝 問候 AJ

+0

我建議你通過在緩存部分工作開始。確保你的對象被服務器響應中的頭部聲明爲可緩存。 – njzk2

回答

1

創建一個全局XML變量和查詢與你的函數調用...

var XML = null; 

function fetchXML(){ 
    $.ajax({ 
     type: "GET", 
     url: "XML/XML.xml", 
     dataType: "xml", 
     success: function(data){ 
      XML = data; 
     }, 
     error:function(){ alert('something went wrong');}) 
} 

function getImage(id) { 
    $(XML).find(id).each(){ ... }; 
} 

funcition getDept(id) { 
    $(XML).find(id).each(){ ... }; 
} 
+0

我似乎無法使它工作,每當我簡單地將fetchXML函數放入時,它就會停止原始JavaScript Ajax XML請求的其餘部分。 – AlpaxJ1

+0

發現問題,需要使用Async:false header for chrome。謝謝你的幫助! – AlpaxJ1