Jquery:Ajax解析XML数据(同步及异步调用)

首先来看一个Jquery的onload的方法:

 

$(document).ready(function() { 
           alert("aaaaa");
 });

 

接下来进入主题了,Jquery Ajax来解析XML数据,我也是新手,今天刚刚有时间试验了一下..

 

加载Jquery包<script type="text/javascript" src="<%=webRoot%>/jquery-1[1].2.6.pack.js"></script>
$.ajax({ 
      url:'/platform/contact/resetStatus.do?actionType=test',      //异步方法
      type: 'POST', 
      dataType: 'xml',//这里可以不写,但千万别写text或者html!!! 
      data: "&name=John",                 //传入的那么参数
      timeout: 1000,                            //延迟1秒执行
      error: function(){                        //返回失败后
      $('#rere').value("请稍候……");
      alert('Error loading XML document'); 
      }, 
      success: function(xml){              //返回成功
       $(xml).find("callcenter_response").each(function(){         //找到根节点
           var id=$(this).children("policy_id");                               //节点名称
           var policy_id=$(this).children("policy_id").text();          //节点值
           var policy_code=$(this).children("policy_code").text();  //节点值
       alert($(this).attr("email")); //这里能显示
callcenter_response下的email属性。
           alert(policy_id);
       });
     } 
    });
public void test(HttpServletRequest request, HttpServletResponse response)
 throws Exception {
  PrintWriter out = response.getWriter();
  response.setContentType("text/xml"); 
  String xml = "<?xml version='1.0' encoding=/'UTF-8/'?><callcenter_response email='8988@qq.com'>";
  xml+="<policy_id>19049059</policy_id><policy_code>000486474153008</policy_code></callcenter_respons   e>";
   out.write(xml);
   //out.print(xml);     //用这么返回xml好像也可以,具体还没有细看呢.
   out.flush();
   out.close(); 
 }

 

Jquery:Ajax解析XML数据(同步及异步调用)

代码

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->           $.ajax({
                async: true, // 默认true(异步请求)
                cache: true, // 默认true,设置为 false 将不会从浏览器缓存中加载请求信息。
                type: "POST", // 默认:GET 请求方式:[POST/GET]
                dataType: "xml", //默认["xml"/"html"] 返回数据类型:["xml" / "html" / "script" / "json" / "jsonp"]
                url: "Test.ashx", // 默认当前地址,发送请求的地址
                data: { key: "value" }, // 发送到服务器的数据
                error: function(xml) { alert('Error loading XML document' + xml); }, // 请求失败时调用
                timeout: 1000, // 设置请求超时时间
                success: function(xml) { // 请求成功后回调函数 参数:服务器返回数据,数据格式.
                    $("#users").empty();
                    // 用Jquery处理xml数据
                    $(xml).find('Table').each(function() {
                        var loginname = $(this).find("Loginname").text();
                        var Name").text();
                        $("#users").append("<li>" + loginname + " - " + name + "</li>");
                    });
                    /*
                    $(xml).find('user').each(function(i) {
                        var loginname = $(xml).find("user loginname").eq(i).text();
                        var user name").eq(i).text();
                        $("#users").append("<p>" + loginname + "</p>" + "<p>" + name + "</p><Br />");
                    }) 
                    $(xml).find("student").each(function(i){
                        var id"); //取对象
                        var id_value=$(this).children("id").text(); //取文本
                        alert(id_value);//这里就是ID的值了。
                        alert($(this).attr("email")); //这里能显示student下的email属性。

                        //最后输出了,这个是cssrain的写法,貌似比macnie更JQ一点
                        $('<li></li>').html(id_value).appendTo('ol');
                    });
                    */
                }
            })
用ashx文件返回XML数据:
代码

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><%@ WebHandler Language="C#" %>

using System;
using System.Web;
using System.Text;
using System.Data;

public class Test : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.StatusCode = 200;
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        DataSet ds = new DataSet("AccountList");
        ds = GetList("Account","AccountId","Loginname,Name",50,1,false, false,"1=1");
        context.Response.ContentType = "text/xml";
        context.Response.Charset = "GB2312";
        context.Response.Clear();
        context.Response.Write("<?xml version=\"1.0\" encoding=\"gbk\"?>\n " + ds.GetXml());

        /*
        StringBuilder sb = new StringBuilder();
        sb.Append("<?xml version=\"1.0\" encoding=\"gbk\"?>");
        sb.Append("<AccountList>");
        sb.Append("<Account><loginname>Loro5</loginname><name>wulu</name></user>");
        sb.Append("</Account>");
        context.Response.Write(sb.ToString());
        */


        context.Response.End();

    }
     
    public bool IsReusable {
        get {
            return false;
        }
    }

}

用JQuery的Ajax加载XML并解析的注意事项

 

1、Content-Type 
   很多时候无法解析就是Content-Type的问题。如果本身就是XML文件,请跳过这一步。 
   动态生成的XML一定要将其设置为text/xml,否则默认就是text/html也就是普通的文本。   常见语言的Content-Type设置: 
   response.setHeader("ContentType","text/xml");  //jsp 
   response.ContentType= "text/xml"; //asp 
   header("Content-Type:text/xml"); //php 
2、xml结构 
   XML一定要封闭的,很重要的! 
<?xml version="1.0" encoding="UTF-8"?> 
<stulist> 
  <student email="lynn@126.com"> 
    <name>zhangsan</name> 
    <id>1</id> 
  </student> 
  <student email="lynn@sina.com"> 
    <name>lisi</name> 
    <id>2</id> 
  </student> 
</stulist> 
3、解析 
   遍历student(这里还是用上面那个XML,子节点是student) 
   $.ajax({ 
     url:'ajax.jsp', 
     type:'GET', 
     dataType:"xml", 
     timeout:1000, 
     error:function(xml){alert('Error Loading XML document' + xml);}, 
     success:function(xml){ 
       $(xml).find("student").each(function(i){ 
         var id = $(this).children("id");  //取对象 
         var id_value = id.text();  //取文本  或者 $("id",xml).text(); 
         alert($(this).attr("email"));  //这里显示student下的email属性】 
         $('<li></li>').html(id_value).appendTo('ol'); 
       }); 
     } 
   }); 
4、禁用缓存 
   如果你直接使用Ajax方法,可以使用cache:false来禁用缓存。 
   如果你使用get或者post方法,可以在url后面加上时间戳:"xml.jsp?timestamp=" + (new Date()); 
   注意:不要使用随机数,因为你无法预料到随机数会不会再随机到...... 
   但是在一切正常的情况下,时间戳是肯定不会重复的。 

 

posted @ 2015-01-11 10:43  贝壳风铃  阅读(517)  评论(0)    收藏  举报