请选择 进入手机版 | 继续访问电脑版
 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1551|回复: 0

原生Ajax 请求

[复制链接]

821

主题

821

帖子

2663

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2663
发表于 2019-8-30 08:44:44 | 显示全部楼层 |阅读模式
  1. function jsAjax(args) {
  2.   var self = this;
  3.   this.options = {
  4.     type: 'GET',
  5.     async: true,
  6.     contentType: 'application/x-www-form-urlencoded',
  7.     url: 'about:blank',
  8.     data: null,
  9.     success: {},
  10.     error: {}
  11.   };
  12.   this.getXmlHttp = function () {
  13.     var xmlHttp;
  14.     try {
  15.       xmlhttp = new XMLHttpRequest();
  16.     } catch (e) {
  17.       try {
  18.         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  19.       } catch (e) {
  20.         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  21.       }
  22.     }
  23.     if (!xmlhttp) {
  24.       alert('您的浏览器不支持AJAX');
  25.       return false;
  26.     }
  27.     return xmlhttp;
  28.   };
  29.   this.send = function () {
  30.     C.each(self.options, function (key, val) {
  31.       self.options[key] = (args[key] == null) ? val : args[key];
  32.     });

  33.     var xmlHttp = new self.getXmlHttp();
  34.     if (self.options.type.toUpperCase() == 'GET') {
  35.       xmlHttp.open(self.options.type, self.options.url + (self.options.data == null ? "" : ((/[?]$/.test(self.options.url) ? '&' : '?') + self.options.data)), self.options.async);
  36.     } else {
  37.       xmlHttp.open(self.options.type, self.options.url, self.options.async);
  38.       xmlHttp.setRequestHeader('Content-Length', self.options.data.length);
  39.     }
  40.     xmlHttp.setRequestHeader('Content-Type', self.options.contentType);
  41.     xmlHttp.onreadystatechange = function () {
  42.       if (xmlHttp.readyState == 4) {
  43.         if (xmlHttp.status == 200 || xmlHttp.status == 0) {
  44.           if (typeof self.options.success == 'function') self.options.success(xmlHttp.responseText);
  45.           xmlHttp = null;
  46.         } else {
  47.           if (typeof self.options.error == 'function') self.options.error('Server Status: ' + xmlHttp.status);
  48.         }
  49.       }
  50.     };
  51.     xmlHttp.send(self.options.type.toUpperCase() == 'POST' ? self.options.data.toString() : null);
  52.   };
  53.   this.send();
  54. };

复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

用户反馈
客户端