AJAX请求

  Ajax即Asynchronous Javascript And XML(异步JavaScript和XML)在 2005年被Jesse James Garrett提出的新术语,用来描述一种使用现有技术集合的‘新’方法,括: HTML 或 XHTML, CSS, JS, DOM, XMLX, 以及最重要的XMLHttpRequest。 [3]  使用Ajax技术网页应用能够快速地将增量更新呈现在界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。

为了快速搭建后端环境,后端采用了Node.js+express进行搭建,只是为了学习使用,没有考虑其他问题。

一、原生的Ajax

1、get请求

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX GET请求</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #90b;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>
</body>
<script>
    // 获取button元素
    const btn=document.getElementsByTagName('button')[0];
    const result=document.getElementById("result");
    btn.onclick=function(){
        // 1创建对象
        const xhr=new XMLHttpRequest();
        // 初始化
        xhr.open('GET','http://127.0.0.1:8000/server');
        // 发送
        xhr.send();
        // 事件绑定处理服务器返回数据
        xhr.onreadystatechange=function(){
            // 此时表明服务器端已经返回所有结果
            if(xhr.readyState==4){
                // 判断响应状态码
                if(xhr.status==200){
                    // 处理结果
                    // 1.响应行
                    console.log(xhr.status);
                    console.log(xhr.statusText);//状态字符串
                    console.log(xhr.getAllResponseHeaders());//所有的响应头
                    console.log(xhr.response);//响应体
                    // 设置result的文本
                    result.innerHTML=xhr.response;
                }else{

                }
            }
        }
    }
</script>
</html>

后端的js代码:

// 引入express
const express=require('express');
// 创建应用对象
const app=express();
// 创建路由规则
app.get('/server',(request,response)=>{
    // 设置响应头,允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
    // 设置响应
    response.send("hello Ajax get");
});

点击按钮后即可以将文本显示在div框内

2、post请求

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax Post请求</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #90b;
        }
    </style>
</head>
<body>
    <div id="result"></div>
</body>
<script>
    const result=document.getElementById('result');
    result.addEventListener("mouseover",function(){
        // 1创建对象
        const xhr=new XMLHttpRequest();
        // 初始化
        xhr.open('POST','http://127.0.0.1:8000/server');
        // 设置请求头
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        //发送
        xhr.send();
        // 也可以设置请求参数
        // xhr.send('a=100&b=200&c=300')
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    result.innerHTML=xhr.response;
                }
            }
        }
    })
</script>
</html>

后端的响应代码:

app.post('/server',(request,response)=>{
    // 设置响应头,允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
    // 设置响应
    response.send("hello Ajax post");
});

3、总结

总之,原生的ajax请求可以分为4步:

(1)首先创建对象:

const xhr=new XMLHttpRequest();

(2)初始化:

xhr.open(method,url);

此处的method可以为'GET'或者'POST',url即为想要访问的资源路径。

(3)发送

  xhr.send();

(4)响应返回数据

xhr.onreadystatechange=function(){};

此回调函数的作用是xhr.readyState状态改变的时候触发该函数,xhr.readyState有四个值,对应四种状态:

0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪

所以在函数中的响应条件应该为xhr.readyState===4,并且当响应状态码为200的时候说明响应成功。

 if(xhr.readyState==4){
                    // 判断响应状态码
                if(xhr.status==200){
                    // 处理结果
                    // 1.响应行
                    console.log(xhr.status);
                    console.log(xhr.statusText);//状态字符串
                    console.log(xhr.getAllResponseHeaders());//所有的响应头
                    console.log(xhr.response);//响应体
                  }
}

 二、使用jQuery发送Ajax请求

首先在前端页面上设置三个button,分别对应get,post和通用请求。

<button>GET</button>
<button>POST</button>
<button>通用型方法ajax</button>

1、GET请求

js代码:

$('button').eq(0).click(function(){
        $.get('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data){
            console.log(data);
        },'json')
    })

2、POST请求

js代码:

 $('button').eq(1).click(function(){
        $.post('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data){
            console.log(data);
        })
    })

3、通用型方法

$('button').eq(2).click(function(){
        $.ajax({
            url:'',
            data:{a:100,b:200},
            type:'GET',
            dataType:'json',
            success:function(data){
                console.log(data);
            },
            timeout:2000,
            error: function(){
                console.log('出错了');
            }
        })
    })

此处type可以为GET或者POST。

4、总结

首先是get方法格式:

$.get(URL,data,function(data,status,xhr),dataType)

各个参数描述如下:

 

post方法与get类似:

$(selector).post(URL,data,function(data,status,xhr),dataType) 

各个参数与上面相同。 

通用性方法格式:

$.ajax({name:value, name:value, ... })

该方法内部通过一个键值对的对象进行发送请求

 参数较多,常用的参数用法已在例子中给出

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值