Ajax请求

作者: 墨马 | 来源:发表于2017-09-07 23:07 被阅读69次

    原生Ajax请求

    一、创建XMLHttpRequest对象

    var xhr = null;
    if(window.XMLHttpRequest){//标准浏览器
        xhr = new XMLHttpRequest();
    }else{//早期的IE浏览器
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    

    二、准备发送请求-配置发送请求的一些行为

    xhr.open('get','text.php',true);
    

    第一个参数:请求方式
    第二个参数:请求文件
    第三个参数: 默认为true表示异步请求

    第三步:执行发送的动作

    xhr.send(null);
    

    get请求方式发送为空
    post发送需要发送到服务器的内容

    第四步:指定回调函数

    xhr.onreadystatechange = function(){          
        if(xhr.readyState == 4){                  
            if(xhr.status == 200){//请求事成功的        
                var data=xhr.responseText;//json               
            }                                     
        }                                         
         console.log("状态t"+xhr.readyState);       
    }
    

    xhr.readyState的返回值和对应含义
    0.对象创建
    1.准备好发送,还没发
    2.已经发送完毕
    3.服务器已返回数据
    4.返回的数据已可以使用
    xhr.status的返回值及含义

    代码 说明
    2xx 成功
    3xx 重定向
    4xx 请求错误
    5xx 服务器错误
    var url = '05open.php?username='+ encodeURIComponent(username) +'&password='+password;
    

    encodeURIComponent(username)防止用户名中有汉字出现乱码

    jQuery方法的Ajax请求

    首先引入jQuery库

    $.ajax({                    
        url:"text.php",         
        dataType:"json",        
        type:"post",            
        data:null,              
        success:function(data){ 
            setcontent(data);   
            console.log(data);  
        },                      
        error:function(e){      
            console.log(e);     
        }                       
    });                                                                                                  
    
    参数 含义
    url 请求的服务器文件
    dataType 要求返回的数据类型
    type 请求方式
    data 传送给服务器的数据
    success:function(data){ } 请求成功执行的函数
    error:function(e){ } 请求失败执行的函数

    data服务器返回的数据
    e错误代码
    data的书写格式
    data:{name:"myName",id:1},

    相关文章

      网友评论

        本文标题:Ajax请求

        本文链接:https://www.haomeiwen.com/subject/hmewjxtx.html