分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

原生ajax类

发布时间:2023-09-06 01:51责任编辑:彭小芳关键词:暂无标签
  • 代码:
    /*@desc ajax请求类@author lee [<complet@163.com>]@param data object{data ???????# 发送到后台的数据,支持json和表单url ????????# 请求的接口地址type ???????# 请求方式 get或postasync ??????# 同步或异步 true:异步 false:同步json ???????# 发送的数据是否是json还是表单 true:json false:表单auth ???????# 后台授权验证 默认为空}*/function ajax(){this.xhrthis.datathis.init = function(){ ???if(window.XMLHttpRequest){ ???????this.xhr=new XMLHttpRequest() ???}else{ ???????this.xhr=new ActiveXObject("Microsoft.XMLHTTP") ???} ???return this}this.before = function(func){ ???this.xhr.addEventListener(‘readystatechange‘,function(){ ???????if(this.readyState < 4){ ???????????func() ???????} ???}) ???return this}this.success = function(func){ ???this.xhr.addEventListener(‘readystatechange‘,function(){ ???????if (this.readyState == 4 && this.status == 200){ ???????????var res ???????????if(this.getResponseHeader(‘content-type‘)===‘application/json‘){ ???????????????res = JSON.parse(this.responseText) ???????????}else{ ???????????????res = this.responseText ???????????} ???????????func(res) ???????} ???}) ???return this}this.error = function(func){ ???this.xhr.addEventListener(‘readystatechange‘,function(){ ???????if(this.readyState == 4 && this.status != 200){ ???????????func() ???????} ???}) ???return this}this.request = function(obj){ ???this.data = obj.data ???var url = obj.url ???var type = obj.type ???var async = obj.async ???var json = (obj.json===true)?true:false ???var auth = obj.auth ???this.init() ???this.xhr.open(type,url,async) ???if(json){ ???????this.xhr.setRequestHeader("Content-type", "application/json") ???????this.data = JSON.stringify(this.data) ???}else{ ???????this.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") ???} ???if(auth){ ???????this.xhr.withCredentials = true ???????this.xhr.setRequestHeader("Authorization", "Basic " + btoa(auth)) ???} ???return this}this.send = function(){ ???this.xhr.send(this.data)}}
  • 用法:
    var xhr = new ajax()var data = {data:‘name=lee‘,url:‘http://localhost/test.php‘,type:‘post‘,async:true,json:false}xhr.request(data).before(function(){console.log(1)}).success(function(data){console.log(data)}).error(function(){console.log(2)}).send()
  • 效果:
  • 原生ajax类

    原文地址:http://blog.51cto.com/12173069/2109281

    知识推荐

    我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
    icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved