ajax前后端交互aletr()值不显示,半天没找到哪里有问题

萌新学代码学到ajax这突然就找不到问题出在哪里了,点击按钮之后页面上没有显示获取到的值

控制台又显示获取到了

img

报错也只显示两端我查了半天好像和代码本身没什么关联的错误

img

希望指点一下问题出在哪里

下面是代码

img

img


function $ajax({method = "get", url, data, success, error}){
    //1.创建ajax对象   
    var xhr = null;   
   try{
       xhr = new XMLHttpRequest();
   }catch(error){
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
   }
   
   //判断如果有数据存在
   if(data){
       data = querystring(data);
   }

   if(method == "get" && data){
       url += "?" + data;
   }

   xhr.open(method, url, true);

   if(method == "get"){
       xhr.send();
   }else{
        //必须在send方法之前,去设置请求的格式
        xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
        xhr.send(data);
       
    xhr.onreadystatechange = function(){
           if(xhr.readyState == 4){
               //判断本次下载的状态码是多少
               if(xhr.status == 200){
                   if(success){
                       success(xhr.responseText);
                    }
               }else{
                   if(error){
                   error("Error:" + xhr.status);
                    }
               }
           }
       }
   }
}
function querystring(obj){
   var str = "";
   for(var attr in obj){
      str += attr + "=" + obj[attr] + "&";
   }
   return str.substring(0, str.length - 1);
}

$ajax函数有个问题,onreadystatechange要放到外面,要不get请求没有状态处理函数,所以没反应,错误是chrome扩展提示的,不是你编写的代码

有帮助麻烦点个采纳【本回答右上角】,谢谢~~有其他问题可以继续交流~

 
    function $ajax({ method = "get", url, data, success, error }) {
        //1.创建ajax对象   
        var xhr = null;
        try {
            xhr = new XMLHttpRequest();
        } catch (error) {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //判断如果有数据存在
        if (data) {
            data = querystring(data);
        }
        if (method == "get" && data) {
            url += "?" + data;
        }
        xhr.open(method, url, true);
        if (method == "get") {
            xhr.send();
        } else {
            //必须在send方法之前,去设置请求的格式
            xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
            xhr.send(data);
        } 
/////放外面,要不只有post请求有效,get请求没有处理函数所以没反应
xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                //判断本次下载的状态码是多少
                if (xhr.status == 200 || 0 == xhr.status) {
                    if (success) {
                        success(xhr.responseText);
                    }
                } else {
                    if (error) {
                        error("Error:" + xhr.status);
                    }
                }
            }
        }
    }
 

ajax默认是异步执行的,当请求没有回来时,alert已经执行了。所以是空,有很小的概率会弹内容出来。除非改成同步调用

alert(result)也没有反应?