zoukankan      html  css  js  c++  java
  • 原生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---数据接收成功后执行传来的函数
  • 相关阅读:
    TreeMap<K,V>类
    2020-3-7学习地图
    Thread类
    Redis-Windows中注册Redis后台守护进程
    Redsi-(error) NOAUTH Authentication required.
    2020-3-6学习地图
    Collection<E>接口
    Map<K,V>接口
    Set接口
    List类
  • 原文地址:https://www.cnblogs.com/cck1223/p/9960824.html
Copyright © 2011-2022 走看看