原生js实现Ajax请求,包含get和post
2024-10-07 00:39:58
现在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)函数。
最新文章
- Basic Calculator II
- .net core 产品开发问题记录
- Gobblin采集kafka数据
- Caffe学习系列(8):solver及其配置
- IIS出现The specified module could not be found解决方法
- 备忘:文本编辑器(z.B. Sublime Text 2)策略,git策略
- 安装Adobe Dreamweaver CS6 免序列号 官方破解版
- Qt环境搭建(Visual Studio)
- 【HDOJ】1098 Ignatius&#39;s puzzle
- Android EventBus
- EncodingUtils 编译不通过
- Android 制作一个网页源代码浏览器(HttpURLConnection)
- POJ 1322 Chocolate
- [置顶] android AIDL 进程间通信
- 从UUID想到的
- 小技巧-ASP.Net session保存在数据库服务器
- VSC 解决红底线问题
- Java反射和注解
- Docker学习计划三:Dockerfile 使用
- windows 模拟用户会话创建进程