Ajax的使用(原生JavaScript和jQuery)

331 阅读1分钟

1.Ajax的核心对象XMLHttpRequest

2.GET方式   发送的数据放在了url当中,大小有限制

3.POST方式   请求数据放在了请求体中,大小理论上没上限,一般用于保密的数据,并且https还会对其内容进行加密

JavaScript原生实现:

步骤:

一.get方式

1.创建Ajax对象

    let xhr = new XMLHttpRequest();

4.监听请求    防止发送的请求已经返回还没有进行监听

    xhr.onreadystatechanges = () => {

    //当xhr对象的readystate属性发生了改变,这个事件就会触发

    //0---> xhr对象已经创建,但是哈吉没有进行一个初始化操作

    //1--->xhr对象已经调用了open

    //2--->xhr已经发送Ajax请求

    //3--->已经返回了部分请求

    //4--->数据已经全部返回

if( xhr.readyState !== 4){
    return;

}

if(xhr.status >=  200 && xhr.status <= 300){

    console.log(xhr.response);

}else{
    console.log('请求失败');

}

2.配置这个对象

    //get方式要将参数追加到url之后

    xhr.open(‘get', './login.php?name=hello' ,true)

3.发送请求

    xhr.send()

二.post方式

let xhr = new XMLHttpRequest();

xhr.onreadystatechanges = () =>{

if( xhr.readyState !== 4){
return;

}

if(xhr.status >= 200 && xhr.status <= 300){

let resp = JSON.parse(xhr.response);

console.log(resp);

}else{
console.log('请求失败');

}

xhr.open(‘post', './login.php?name=hello' ,true)

//post在发送给之前需要设定一个请求头,指定body内的数据是何格式

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xhr.send('user=hello&password=123456');    

jQuery实现

jQuery提供的Ajax非常简单

$.ajax({

    url('./login.php'),

    type:'post',

    data:{

        name:'name',

        password:'password'

    }

    dataType:'json',

    success:function(res){

        console.log(res);

    }

});