在jquery ajax中返回xml

我的问题是我想将一个xml文件从服务器返回给客户端并使用jquery的jjax函数解析它。 这是代码:

客户:

$("#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 ''; echo ""; echo "Someone"; echo ""; 

我有一个空白警报,我不知道为什么?


好的,我找到了。 我的php文件是这种forms

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

other.php文件是我上面发布的文件。 我剪切/粘贴标题,以便最终的php文件

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

和其他.php

 echo ''; echo ""; echo "Someone"; echo ""; 

现在它完美无缺。 谢谢你的快速回复!

这工作正常

Post.php文件

 if($_GET['id']!=""){ $array = array('satyam' => 'satyam', 'class' => 'B.TECH', 'company' => 'Ranosys'); } $new =''; foreach($array as $key => $values){ $new .= "<$key>$values"; } echo $new.''; ================= 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); } }); } 

试试这个: var data = $(xml).find('doctor').text()

在您的示例中,’xml’不是jQuery对象。

你需要解析这个XML(我真的不明白为什么,但是……),你可以这样做:

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

再见。 🙂

你必须改变你的function:

 $("#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); } }); }); 

if(window.DOMParser){的原因是IE在解析时遇到问题。