现在web从服务器请求数据,很多用到Ajax,不过都是用的JQuery封装好的,之前做项目,由于无法引用JQuery,所以就只能用原生了,话不多说,请看代码。

 /*-------------------Ajax start--------------------*/

 function ajax(options) {
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || "json";
var params = formatParams(options.data);
var xhr; //创建 - 第一步
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if(window.ActiveObject) { //IE6及以下
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} //连接 和 发送 - 第二步
if (options.type == "GET") {
xhr.open("GET", options.url + "?" + params, true);
xhr.send(null);
} else if (options.type == "POST") {
xhr.open("POST", options.url, true);
//设置表单提交时的内容类型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
} //接收 - 第三步
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var status = xhr.status;
if (status >= 200 && status < 300 || status == 304) {
options.success && options.success(xhr.responseText, xhr.responseXML);
} else {
options.error && options.error(status);
}
}
}
} //格式化参数
function formatParams(data){
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
arr.push(("v=" + Math.random()).replace(".",""));
return arr.join("&");
} /*-------------------Ajax end-------------------*/

自己封装Ajax,主要分三步:

第一步:创建需要的对象,这里主要用到的是XMLHttpRequest,注意需要考虑早期的IE;

第二步:连接和发送;

第三步:接收;

这里为了格式化请求参数,封装了一个formatParams(data)函数。

最新文章

  1. Basic Calculator II
  2. .net core 产品开发问题记录
  3. Gobblin采集kafka数据
  4. Caffe学习系列(8):solver及其配置
  5. IIS出现The specified module could not be found解决方法
  6. 备忘:文本编辑器(z.B. Sublime Text 2)策略,git策略
  7. 安装Adobe Dreamweaver CS6 免序列号 官方破解版
  8. Qt环境搭建(Visual Studio)
  9. 【HDOJ】1098 Ignatius&#39;s puzzle
  10. Android EventBus
  11. EncodingUtils 编译不通过
  12. Android 制作一个网页源代码浏览器(HttpURLConnection)
  13. POJ 1322 Chocolate
  14. [置顶] android AIDL 进程间通信
  15. 从UUID想到的
  16. 小技巧-ASP.Net session保存在数据库服务器
  17. VSC 解决红底线问题
  18. Java反射和注解
  19. Docker学习计划三:Dockerfile 使用
  20. windows 模拟用户会话创建进程

热门文章

  1. NativeContainer
  2. nginx +域名
  3. core python
  4. MariaDB(第三章)select
  5. servlet学习之servletAPI编程常用的接口和类
  6. python 爬虫 urllib模块 url编码处理
  7. 传统Java Web(非Spring Boot)、非Java语言项目接入Spring Cloud方案--temp
  8. MySQL 中 savepoint 的使用
  9. Git上传相关资料
  10. Redis安全策略