Ajax::prototype 源码解读

2019-06-03 08:36:20刘景俊

     我想很多时候,java 限制了 js 的创意。 
   */ 
  setOptions: function(options) { 
    this.options = { 
      method:       'post', 
      asynchronous: true, 
      parameters:   '' 
    }.extend(options || {}); 
  } 



/** 
 * Ajax.Request 封装 XmlHttp 
 */ 
Ajax.Request = Class.create(); 

/** 
 * 定义四种事件(状态), 参考http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/readystate_1.asp 
 */ 
Ajax.Request.Events = 
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; 

/** 
 * 
 */ 
Ajax.Request.prototype = (new Ajax.Base()).extend({ 
  initialize: function(url, options) { 
    this.transport = Ajax.getTransport(); 
    this.setOptions(options); 

    try { 
      if (this.options.method == 'get') 
        url += '?' + this.options.parameters + '&_='; 

     /** 
      * 此处好像强制使用了异步方式,而不是依照 this.options.asynchronous 的值 
      */ 
      this.transport.open(this.options.method, url, true); 

     /** 
      * 这里提供了 XmlHttp 传输过程中每个步骤的回调函数 
      */ 
      if (this.options.asynchronous) { 
        this.transport.onreadystatechange = this.onStateChange.bind(this); 
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10); 
      } 

      this.transport.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); 
      this.transport.setRequestHeader('X-Prototype-Version', Prototype.Version); 

      if (this.options.method == 'post') {