request.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //= require amcharts/util
  2. //= require amcharts/ajax/response
  3. //= require_self
  4. AmCharts.RB.Ajax.Request = AmCharts.RB.Util.Class.create({
  5. response: null,
  6. initialize: function(url, params, method, on_state_change)
  7. {
  8. this.transport = this.get_transport();
  9. this.url = url;
  10. this.method = method ? method.toUpperCase() : 'GET';
  11. this.params = AmCharts.isString(params) ? params : AmCharts.RB.Util.to_query_string(params);
  12. if (this.method != 'GET' && this.method != 'POST') {
  13. // simulate other verbs over post
  14. this.params += (this.params ? '&' : '') + "_method=" + this.method;
  15. this.method = 'POST';
  16. }
  17. if (this.params && this.method === 'GET') {
  18. // when GET, append parameters to URL
  19. this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + this.params;
  20. }
  21. this.transport.open(this.method.toUpperCase(), this.url, true);
  22. this.response = new AmCharts.RB.Ajax.Response(this.transport);
  23. if (on_state_change && AmCharts.RB.Util.is_function(on_state_change)) {
  24. this.transport.onreadystatechange = on_state_change;
  25. }
  26. this.set_request_headers();
  27. this.transport.send(this.method === 'POST' ? this.params : null);
  28. },
  29. get_transport: function()
  30. {
  31. return AmCharts.RB.Util.try_these(
  32. function() {return new XMLHttpRequest()},
  33. function() {return new ActiveXObject('Msxml2.XMLHTTP')},
  34. function() {return new ActiveXObject('Microsoft.XMLHTTP')}
  35. ) || false;
  36. },
  37. set_request_headers: function()
  38. {
  39. var headers = {
  40. 'X-Requested-With': 'XMLHttpRequest',
  41. 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  42. };
  43. if (this.method == 'POST')
  44. {
  45. headers['Content-type'] = "application/x-www-form-urlencoded; charset=UTF-8";
  46. /* Force "Connection: close" for older Mozilla browsers to work
  47. * around a bug where XMLHttpRequest sends an incorrect
  48. * Content-length header. See Mozilla Bugzilla #246651.
  49. */
  50. if (this.transport.overrideMimeType && (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
  51. headers['Connection'] = 'close';
  52. }
  53. for (var name in headers) {
  54. this.transport.setRequestHeader(name, headers[name]);
  55. }
  56. }
  57. });