2011-05-18 43 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); 
     } 
    }); 
}