• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
红炉一点雪cck
博客园    首页    新随笔    联系   管理    订阅  订阅

原生js---ajax的封装插件.js---(对get和post做了兼容)

function ajax(method,url,data,fn){
    // 1、创建对象
    var xhr=null;
    try{
    xhr=new XMLHttpRequest();
    }catch(e){
    xhr=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    // 2、open方法
    if(method=="get"&&data){
      url=url+"?"+data;
    }
    xhr.open(method,url,true);
    
    // 3、send方法
    if(method=="get"){
        xhr.send()
    }else{
    // post请求时执行
    // 声明发送的数据类型
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
        xhr.send(data);
    }
    
    // 4、接收数据
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if (xhr.status==200) {
            // 数据接收成功后执行传来的函数
            fn(xhr.responseText)
            }else{
            alert("错误"+xhr.status)
            }
        }
    }
}



注:function ajax(method,url,data,fn){}
method----方法
url---路径
data---数据,不用传数据时,函数传该参数""
fn---数据接收成功后执行传来的函数

 

posted @ 2018-11-14 22:26  红炉一点雪cck  阅读(534)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3