封装js发送http请求
来源:互联网 发布:域名备案信息 编辑:程序博客网 时间:2024/06/05 10:16
封装js发送http请求
var http = {};http.quest = function (option, callback) { var url = option.url; var method = option.method; var data = option.data; var timeout = option.timeout || 0; var xhr = new XMLHttpRequest(); (timeout > 0) && (xhr.timeout = timeout); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 400) { var result = xhr.responseText; try {result = JSON.parse(xhr.responseText);} catch (e) {} callback && callback(null, result); } else { callback && callback('status: ' + xhr.status); } } }.bind(this); xhr.open(method, url, true); if(typeof data === 'object'){ try{ data = JSON.stringify(data); }catch(e){} } xhr.send(data); xhr.ontimeout = function () { callback && callback('timeout'); console.log('%c连%c接%c超%c时', 'color:red', 'color:orange', 'color:purple', 'color:green'); };};http.get = function (url, callback) { var option = url.url ? url : { url: url }; option.method = 'get'; this.quest(option, callback);};http.post = function (option, callback) { option.method = 'post'; this.quest(option, callback);};
使用方法
//普通get请求http.get('http://www.baidu.com',function(err,result){});//定义超时时间(单位毫秒)http.get({url:'http://www.baidu.com',timeout:1000},function(err,result){});//post请求http.post({url:'http://www.baidu.com',data:'123',timeout:1000},function(err,result){});
1 0
- 封装js发送http请求
- Node.js发送HTTP请求
- node js 发送http请求
- //封装发送http请求的工具包
- node.js发送http(get,post)请求
- HttpClient 发送 HTTP、HTTPS 请求的简单封装
- HttpClient 发送 HTTP、HTTPS 请求的简单封装
- HttpClient 发送 HTTP、HTTPS 请求的简单封装
- 封装C#发送http请求成功后的callback
- 优雅地封装使用rxjava2+retrofit2发送http请求
- Node.js中http 接收get请求、接收post请求、发送get请求、发送post请求
- Node.Js http模块(一)-发送http请求实例
- cocos2d-js 中封装HTML5和Native的Http请求
- Android封装Http请求
- Block封装http请求
- http请求封装
- 简单封装 HTTP 请求
- go http 请求封装
- JAVA实现链表的基本操作
- Hibernate学习记录4 缓存机制
- [已解决] 收到广播无法启动activity
- spring JPA 实体创建 分页排序 时间比较
- 博客第一天!
- 封装js发送http请求
- 去哪儿网-后台开发-一面
- ML的45问(3)——神经网络与感知器法则、反向传播算法
- SSL 2646_线段树练习题三_线段树
- 遗忘---近日零散知识点总结
- uva 10200 Prime Time
- codeforces 788 A. Functions again(最大连续子序列和)
- 三维扫描仪[9]——如何设计一台云台式扫描仪(初步软件设计)
- checkbox的只读设置