XML解析错误:xml处理指令不在外部实体的开始部分

在学习《锋利的jQuery》第六章,jquery与Ajax中

$.get()方法获取XML文档信息时遇到这样一个问题:

下面的代码执行后无法获取到XML文档中的信息

$(function(){

   $("#send").click(function(){

                $.get("get2.jsp", {

                               username :  encodeURI( $("#username").val() ) ,

                               content :  encodeURI( $("#content").val() )

                       }, function (data, textStatus){  

                              var username = $(data).find("comment").attr("username");

                              var content = $(data).find("comment content").text();

                              username =  decodeURI(username);

                              content = decodeURI(content);   

                              var txtHtml = "<div class='comment'><h6>"+username+":              </h6><pclass='para'>"+content+"</p></div> "; 

                              $("#resText").html(txtHtml); // 把返回的数据添加到页面上

                       });

         })

})

对应的jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<% 

String username = request.getParameter("username"); 

String content = request.getParameter("content"); 

response.setContentType("text/xml"); 

out.println("<?xml version='1.0' encoding='UTF-8'?>"); 

out.println("<comments>"); 

out.println("<comment username='"+username+"'>"); 

out.println("<content>"+content+"</content>"); 

out.println("<comment>"); 

out.println("</comments>");

%>

打开http://localhost:8080/jsp/demo3-get/get2.jsp文件后,显示如下内容:

XML 解析错误:XML 或文本声明不在实体的开头

位置:http://localhost:8080/jsp/demo3-get/get2.jsp

行 2,列 1:

<?xml version='1.0' encoding='UTF-8'?>

^

解决方法有两种(方案来自博客园 ):

一种当然是注释掉,它不会影响xml文件结构;

二是加入out.clear(),清除页面上所有东西(因为上面的错误可能是由于不适当的空格或空行引起的,但这些元素又是我们在文档中看不到的)

out.clear() 位置为:

response.setContentType("text/xml");的后面 ,out.println("<?xml version='1.0' encoding='UTF-8'?>");的前面。

同理,PHP中的解决方法也是同样的

解决办法:在php页面头部增加ob_clean();就可以正常显示

解决方法原理:在要输出xml之前,先清空缓存区,ob_clean();就能够正常输出数据了


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容