【问题标题】:How to manipulate dataType xml when using $.ajax?使用 $.ajax 时如何操作 dataType xml?
【发布时间】:2011-05-31 02:05:11
【问题描述】:

在使用$.ajax 时,我在使用 XML 数据类型时遇到了一些困难。

我创建了一个 PHP 文件 (test.php):

<script type="text/javascript" src="js/jquery.min.js"></script>

<?php        
   //this code will show some xml tag when there is an ajax call 
   if(isset($_REQUEST['t']) && $_REQUEST['t']==1){
      echo "<result >";
      echo "<info>Tristan Jun</info>";
      echo "<age>22</age>";
      echo "</result>";
      return;
    }
?>

<script>
$(document).ready(function(){
    $('#testing').click(function(){
        alert('uuuuuuu');
        var content = $.ajax({
           type:"GET",
           url :"test.php",
                   data:'t=1',
           dataType:"**html**",
           async:false,
           success:function(content){           
                cont = $(content);
                inf     = cont.find('info').text();
                age = cont.find('agel').text();
            //alert('inf');
                $('#show1').html(inf);
                $('#show2').html(total);
           },
           error: function(){
                alert('THERE'S AN ERROR');
           }
         }).**responseHTML**;
      });//end of click
 });//end of ready
 </script>

 <a id="testing" href="#">TEST</a>

 <div id="show1"></div>
 <div id="show2" style="background-color:#069"></div>

这是我对这个例子的描述:

  • 当我点击“TEST”按钮时,它会调用 AJAX 来显示 PHP 代码的结果
  • 在 AJAX 调用中,我只想在下面的 2 个&lt;div&gt; 中显示每个标签的文本(#show1#show2

上面的示例在$.ajax 中使用了 dataType HTML,它适用于这种类型。但是当我尝试使用 dataType XML 时,它没有显示任何内容。

所以,我希望你们给我一些想法或一些关于这个问题的参考。

【问题讨论】:

    标签: php jquery xml ajax


    【解决方案1】:

    如果您发布的整个代码是test.php的内容,则响应不能是有效的xml。

    输出将以 &lt;result/&gt; 结尾,但以 &lt;script/&gt; 开头。 (XML 需要有一个根元素)。

    我建议使用 output_buffer,如果请求来自 ajax,则在回显 xml 之前丢弃缓冲区的内容。(或者只是将 PHP 代码放在顶部)

    【讨论】:

    • 耶!!,非常感谢。它完美地工作:D。我忘记了 xml 的结构 ^^
    猜你喜欢
    • 1970-01-01
    • 2016-02-08
    • 2014-10-30
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2013-08-01
    相关资源
    最近更新 更多