美文网首页
ajax 的实现

ajax 的实现

作者: 夜幕小草 | 来源:发表于2016-11-25 13:04 被阅读21次

var $ = {};

$.ajax = ajax;

function json2url(json){

var arr = [];

//添加随机因子

json.t = Math.random();

for(var name in json){

//进行编码

arr.push(name + "=" + encodeURIComponent(json[name]));

}

return arr.join("&");

}

//options:url,type,timeout,data,success,error

function ajax(options){

options = options || {};

if(!options.url){

return ;

}

options.type = options.type || "get";

options.timeout = options.timeout || 0;

options.data = options.data || {};

var str = json2url(options.data);

//1 创建

if(window.XMLHttpRequest){

var xhr = new XMLHttpRequest();

} else {

var xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

if(options.type == "get"){

//2 连接 open(方式,地址,是否异步)

xhr.open("get",options.url+"?"+str,true);

//3 发送 send   xhr.send(null);

xhr.send();

} else{

//2 连接 open(方式,地址,是否异步)

xhr.open("post",options.url,true);

//设置请求头

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

//3 发送 send   xhr.send(null);

xhr.send(str);

}

//4 接收

xhr.onreadystatechange = function(){

if(xhr.readyState == 4){//完成

clearTimeout(timer);

//http状态  [200,300) 304

if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){

//成功

options.success && options.success(xhr.responseText);

} else {

//失败

options.error && options.error(xhr.status);

}

}

};

if(options.timeout){

var timer = setTimeout(function(){

alert("超时了");

xhr.abort();//终止请求

},options.timeout);

}

}

相关文章

  • Ajax异步请求[17.7.10]

    Ajax异步请求 Ajax全称为Asynchronous Javascript and XML。通过Ajax实现了...

  • 2018-01-19 关于房屋列表页的实现方法

    1. 首先使用AJAX 整个页面获取数据的方式是Ajax实现的,在Joomla中,Ajax的实现方法是在modul...

  • ajax

    ajax() ajax的实现 $.ajax({ //发送请求地址(默认当前页地址) url:String, //请...

  • Ajax

    标签: Ajax 正文 一、实现一个原生Ajax 二、Ajax状态 三、将原生的 ajax 封装成 promise

  • JavaScript-Ajax原理

    一.JavaScript单线程 二.实现Ajax 1.XMlHttpRequest实现Ajax 2.jQuery实...

  • Ajax和跨域总结

    Ajax(JavaScript实现) 简介 Ajax(Async Javascript And Xml):异步Js...

  • Ajax

    Ajax简介 通过AJAX (Asynchronous JAvaScript and XML) 实现异步刷新 用于...

  • AJAX POST请求实现/AJAX封装/node/RESTfu

    AJAX POST请求实现 AJAX封装 JSONP node.js 扩展

  • xdl11

    短信验证如何实现 调用短信平台接口实现 使用阿里大于。 ajax介绍 AJAX即Asynchronous Java...

  • 三、原生JS发送Ajax请求

    一、Ajax实现步骤 使用Ajax技术实现异步交互: 创建XMLHttpRequest对象(根据浏览器的不同创建方...

网友评论

      本文标题:ajax 的实现

      本文链接:https://www.haomeiwen.com/subject/tmwipttx.html