1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* 
  Mootools AJAX extensions for Rails compliance
  Requires Element, String and Array CNET extensions  http://clientside.cnet.com/libraries/cnets-global-framework/mootools-extended/
*/

Ajax.implement({

  // Directly evaluate the remote AJAX response
  evalResponse: function() {
    return eval(this.transport.responseText);
  },
  
  // retrieve an HTTP response header 
  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) { return null }
  },
  request: function(){
    switch ($type(this.options.postBody)){
      case 'element': this.options.postBody = $(this.options.postBody).toQueryString(); break;
      case 'object': this.options.postBody = Object.toQueryString(this.options.postBody); break;
      case 'string': break;
      default: this.options.postBody = null;
    }

    // simulate other verbs over post
    if (!['get', 'post'].test(this.options.method) && this.options.postBody) {
      this.options.postBody += '&_method=' + this.options.method;
      this.options.method = 'post';
    }

    return this.send(this.url, this.options.postBody);
  },
  send: function(url, data) {
    this.fireEvent('onRequest');
   
    this.transport.open(this.options.method, url, this.options.async);
    this.transport.onreadystatechange = this.onStateChange.bind(this);
    this.setHeaders({'X-Requested-With': 'XMLHttpRequest'});
    
    // These headers are required by Rails for the MIME respond_to functionality
    this.setHeaders({'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'});
    
    this.setHeaders(this.options.headers);
    if (this.options.method == 'post'){
      this.setHeaders({'Content-type' : 'application/x-www-form-urlencoded'});
      if (this.transport.overrideMimeType) this.setHeaders({'Connection': 'close'});
    }
    this.transport.send(data);
    return this;
  },
  onComplete: function() {
    if (this.options.update) $(this.options.update).setHTML(this.transport.responseText);
    if (this.options.evalScripts) this.evalScripts.delay(30, this);
    /* evalulate remote response directly if the content type matches for javascript */
    if ((this.getHeader('Content-type') || '').strip().match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
        this.evalResponse();
  }

});