2011-05-18 35 views
6

我的問題是我想從服務器返回一個xml文件返回給客戶端,並使用jQuery的ajax函數解析它。這是代碼:在jQuery中返回xml ajax

客戶:

$("#submit").click(function(){   
    $.ajax({ 
     type: "POST", 
     url: "search.php", 
     data: "whatever", 
     dataType: "xml", 
     async: false, 
     success: function(xml){ 
      var data = $('doctor',xml).text(); 
      alert(data); 
     } 
    }); 
}); 

服務器(PHP文件),

header('Content-type: text/xml'); 
echo '<?xml version="1.0" encoding="utf-8"?>'; 
echo "<tables>"; 
echo "<doctor>Someone</doctor>"; 
echo "</tables>"; 

我有一個空白的警覺,我不知道爲什麼?


好的我找到了。我的php文件是這種形式

//some code 
include("other.php"); 
//some other code 

其中other.php文件是我張貼在上面的文件。我剪切/粘貼頭,因此最終的PHP文件將是

//some code 
header('Content-type: text/xml'); 
include("other.php"); 
//some other code 

和other.php

echo '<?xml version="1.0" encoding="utf-8"?>'; 
echo "<tables>"; 
echo "<doctor>Someone</doctor>"; 
echo "</tables>"; 

現在的作品完美。感謝您的快速回復!

+0

是否$(XML).find( 「醫生」)工作嗎? – 2011-05-18 23:20:02

回答

1

試試這個:var data = $(xml).find('doctor').text()

在你的榜樣, 'XML' 不是一個jQuery對象。

+0

這不會在IE瀏覽器工作,每個http://stackoverflow.com/questions/562283/jquery-find-doesnt-return-data-in-ie-but-does-in-firefox-and-chrome – Avitus 2011-05-18 23:41:06

+0

ty爲快速回復!不工作 – 2011-05-18 23:45:15

0

您需要解析這個XML(我真的不明白爲什麼,但是......),你可以做呢:

$(xml).find('doctor').text(); 

再見。 :)

0

你必須改變你的函數是:

$("#submit").click(function(){  
    $.ajax({ 
     type: "POST", 
     url: "search.php", 
     data: "whatever", 
     dataType: "xml", 
     async: false, 
     success: function(xml){ 

      var xmlDoc; 

      if (window.DOMParser) { 
       parser = new DOMParser(); 
       xmlDoc = parser.parseFromString(xml, "text/xml"); 
      } 
      else {// Internet Explorer 
       xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
       xmlDoc.async = "false"; 
       xmlDoc.loadXML(xml); 
      } 
      var $response = $(xmlDoc); 
      var data = $response.find("doctor").text() 

      alert(data); 
     } 
    }); 
}); 

的原因如果(window.DOMParser){是,你必須與IE做解析的問題。

+0

不工作。我在firefox 4上運行應用程序。我嘗試了IE9,但是它根本沒有顯示警報。 – 2011-05-18 23:44:49

2

這是工作的罰款

post.php中文件

if($_GET['id']!=""){  
    $array = array('satyam' => 'satyam', 
        'class' => 'B.TECH', 
        'company' => 'Ranosys'); 
} 

$new ='<?xml version="1.0" encoding="iso-8859-1"?><data>'; 
foreach($array as $key => $values){ 
    $new .= "<$key>$values</$key>"; 
} 
echo $new.'</data>'; 

================= 

function load_data(){ 
    $.ajax({ 
     url: "post.php", 
     async: false, // stop browser for another activity 
     data: "id=satyam", 
     // dataType :'xml', 
     error: function(e, b, error) { 
      for(var i in e){ 
       // alert(i); 
      } 
      alert(e.respone); 
     }, 
     success: function(msg) { 
      //alert($response); 
      var data = $(msg).find("satyam").text(); 
      alert(data); 
     } 
    }); 
}