2017-02-17 98 views
1

我是新來的ajax。我想創建一個簡單的網頁,其中包含一個按鈕,如果點擊返回圖像動態。但responseXML返回空值。下面是JavaScript代碼的一部分:Resposexml返回空值

function process() 
{ 
    if(xmlhttp.readyState==4 || xmlhttp.readyState==0) 
    { 
     xmlhttp.open("GET","image.php",true); 
     xmlhttp.onreadystatechange = handleserverresponse; 
     xmlhttp.send(); 
    }else{ 
     setTimeout('process()',1000); 
    } 
} 

function handleserverresponse() 
{ 
    if(xmlhttp.readyState==4){ 
     if(xmlhttp.status==200){  
      xmlResponse = xmlhttp.responseXML; 
      imag = xmlResponse.documentElement.firstChild.data; 
      document.getElementById("divimg").innerHTML=imag; 
     } 
     else{ 
      alert("something went wrong"); 
     } 
    } 

這裏是PHP代碼:

<?php 
header('Content-Type:text/xml'); 
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'; 

echo "<res>"; 
echo "<img src="a.jpg"/>"; 
echo "</res>"; 

?> 

回答

0

原因responseXML的是零,因爲在PHP文件是錯誤的。 我想我們不能在內容類型爲xml時發送HTML標籤。相反,我們可以做的是回聲圖像的源代碼,並修改JavaScript文件以採用該源並使用img標籤進行顯示。

0
Your HTTP request is asynchronous. xmlhttp.responseXML won't have some value until xmlhttp.readyState has the value of 4. 

var url = "http://localhost/xml.php?type=xml"; 
var xmlhttp; 
if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
} 
else if (window.ActiveXObject) { 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 
if (xmlhttp) { 
    xmlhttp.open("GET", url, true); 
    xmlhttp.setRequestHeader('Content-Type', 'text/xml'); 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4) { 
      alert(xmlhttp.responseXML); 
     } 
    }; 
    xmlhttp.send(); 
} 
Additionaly, I don't think you need the setRequestHeader line. XML MIME type is required for response, not for request. Also, please respect good coding practices (don't forget var, DRY, etc.) 
+0

你剛剛複製了那個代碼,因爲在我的程序readystate已經是4了,你可以看到。我在另一篇文章中看到了幾乎相同的答覆。 –