[转帖]Mootools源码分析-35 -- Request.XML&Request.JSON

原帖地址:http://space.flash8.net/space/?uid-18713-action-viewspace-itemid-407569

原作者:我佛山人

 

代码
//响应输出为JSON的Ajax请求类
Request.JSON = new Class({
    
//继承自Request
    Extends: Request,
    options: {
        
//是否强制返回的JSON为严格格式
        secure: true
    },

    
//覆盖父类构造函数
    initialize: function(options)    {
        
//调用父类同名方法
        arguments.callee.parent(options);
        
//设置HTTP头部信息
        this.headers.extend({'Accept''application/json''X-Request''JSON'});
    },

    
//请求成功,覆盖Request类的同名方法
    success: function(text)    {
        
//添加解释完的JSON对象到响应对象
        this.response.json = JSON.decode(text, this.options.secure);
        
//调用父类方法,触发成功事件
        this.onSuccess(this.response.json, text);
    }
});

/*
自己扩展的,用于响应输出为XML的Ajax请求类
主要是为返回的xml对象附加支持XPath的selectNodes和selectSingleNode方法
因为IE本身已经支持这两方法,所以主要是针对支持XPath的其它浏览器
document.evaluate方法的用法可参考以下网址:
http://developer.mozilla.org/en/docs/DOM:document.evaluate
http://wiki.mozcn.org/index.php/Firefox:Dive_Into_Greasemonkey/4.6._Doing_something_for_every_element_with_a_certain_attribute
*/
Request.XML 
= new Class({

    
//继承自Request
    Extends: Request,

    
//请求成功,覆盖Request类的同名方法
    success: function(text, xml)    {
        
//因为IE本身已经支持这两方法,所以主要是针对支持XPath的其它浏览器
        if(Browser.Features.xpath)    {
            
//扩展实现selectNodes方法
            xml.selectNodes = function(xpath)    {
                
var nodes = [], node;
                
//几个参数的意义
                var result = this.evaluate(xpath, thisthis.createNSResolver(this.documentElement), XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
                
if (result)    while(node = result.iterateNext()) nodes.push(node);
                
return nodes;
            }; 
            
//扩展实现selectSingleNode方法
            xml.selectSingleNode = function(xpath)    {
                
var result = this.evaluate(xpath, thisthis.createNSResolver(this.documentElement), 9null);
                
return (result && result.singleNodeValue) ? result.singleNodeValue : [];
            };
        }
        
//调用父类方法,触发成功事件
        this.onSuccess(xml, text);
    }
});

 

posted @ 2009-11-27 14:18  webgis松鼠  阅读(404)  评论(0编辑  收藏  举报