Ajax学习

简介

Asynchronous JavaScript + XML(异步JavaScript和XML), 其本身不是一种新技术,而是用来描述一种使用现有技术集合的‘新’方法

特点

优点:1.可以无需刷新页面而与服务器端进行通信
2.允许根据用户事件来更新部分页面内容
缺点:1.没有浏览历史,不能回退
2.存在跨域问题
3.搜索引擎优化不友好

HTTP协议

HTTP协议详解: 博客地址

请求报文

格式:

请求行:	请求类型:get/post
				URL路径
				HTTP协议请求行版本
请求头:	Host: baidu.com   
				Cookie: name=baidu
				Content-type:   (类型)
				User-Agent:       
空行:固定必须要有
请求体:

响应报文

行: HTTP/1.1 协议版本
		响应状态码 200/500/404/403
		响应状态字符串  ok/....
头:	Content-Type: text/html;charset=utf-8
		Content-length: 2048
		Content-encoding: gzip
空行:
体: 主要返回结果   <html lang="en">
						<head>
						</head>
						<body>
    					    <h1>hello</h1>
						</body>
				</html>

GET请求

server.js

原生Node.js写服务器app的缺点:路由不方便制作;静态资源服务不方便;页面呈递不方便。因此引入express框架(npm install express --save)

//1.引入express框架
const express= require('express');

//2.创建应用对象
const app=express();

//3.创建路由规则
//request是对请求报文的封装
//response是对响应报文的封装
app.get('/server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader("Access-Control-Allow-Origin","*");
    //设置响应体
    response.send("hello AJAX");
});

//4.启动服务器,监听指定端口
app.listen(8000,()=>{
    console.log("服务已启动,8000 端口监听中...");
});

在这里插入图片描述

GET.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>GET请求</title>
    <!-- 点击按钮时,将响应体的内容传到div中 -->
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 2px solid yellowgreen;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    
    <script>
        //获取button元素
        const btn=document.getElementsByTagName("button")[0];

        // 将响应体的结果展示在div中
        const result=document.getElementById("result");

        btn.onclick=function(){
            //1.创建异步对象
            const xhr = new XMLHttpRequest();
            //XMLHttpRequest 用于在后台与服务器交换数据
            
            //2.初始化,设置请求方法和url
            xhr.open("GET",'http://localhost:8000/server');
            // xhr.open("GET",'http://localhost:8000/server?a=100&b=200&c=300');
            // 在url后面缀参数 ?分割然后加上参数名字和值,若有多个参数用&分割
            //3.发送
            xhr.send();
            //4.事件绑定  处理服务端返回的结果
            /* onreadystatechange
                on: 当...时候
                readystate:对象中的属性,表示状态0(未初始化),1(open方法调用完毕),2(send方法调用完毕),3(服务端返回了部分接口),4(服务端返回了所有接口)
                change:改变
            */
            xhr.onreadystatechange = function(){
                //判断
                if(xhr.readyState===4){
                    //判断响应状态码 200 404 403 401 500
                    //2开头的都表示响应成功(200-299)
                    if(xhr.status===200){
                        //处理结果 行、头、空行、体
                        // 响应
                        console.log(xhr.status);//状态码
                        console.log(xhr.statusText);//状态字符串
                        console.log(xhr.getAllResponseHeaders());//所有响应头
                        console.log(xhr.response);//响应体

                        // 设置result的文本 该操作可以
                        result.innerHTML=xhr.response;
                        
                    }
                }
            }
        }
    </script>
</body>
</html>

在这里插入图片描述
在这里插入图片描述

设置请求体信息

这里介绍的是设置url参数
在Ajax中传递参数——在url后面缀参数

            xhr.open("GET",'http://localhost:8000/server?a=100&b=200&c=300');
            // 在url后面缀参数 ?分割然后加上参数名字和值,若有多个参数用&分割

在这里插入图片描述

POST请求

server.js

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

POST.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>POST请求</title>
    <!-- 当鼠标放在div上时向服务端发post请求,并将结果展示到div中 -->
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 2px solid yellowgreen;
        }
    </style>
</head>
<body>
    <div id="result"></div>
</body>
<script>
    //获取元素对象
    const result = document.getElementById("result");
    //绑定事件
    result.addEventListener("mouseover",function(){
        //1.创建对象
        const xhr = new XMLHttpRequest();
        //2.初始化 设置类型与url
        xhr.open("post","http://localhost:8000/server");
        //3.发送
        xhr.send();
        //4.事件绑定
        xhr.onreadystatechange = function(){
            //判断
            if(xhr.readyState===4){
                if(xhr.status===200){
                    //处理服务端返回的结果
                    result.innerHTML =xhr.response;
                }
            }
        }
    })
</script>
</html>

在这里插入图片描述

设置请求体信息

xhr.send("a=100&b=200&c=300"); 

在这里插入图片描述

设置请求头信息

// 设置请求头 (必须在open后,send前)
        // Content-Type设置请求体内容的类型
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.setRequestHeader("name","guigu");//也可以自定义请求头

在这里插入图片描述

响应JSON

server.js

app.all('/json-server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader("Access-Control-Allow-Origin","*");
    // 响应一个数据
    const data={
        name:'李四'
    }
    // 对对象进行字符串转换
    let str=JSON.stringify(data);
    //设置响应体
    response.send(str);
});

JSON.html

<body>
    <div id="result"></div>
</body>
<script>
    const result=document.getElementById("result");
    //绑定键盘按下事件
    window.onkeydown=function(){
        // 发送请求
        const xhr=new XMLHttpRequest();
        //初始化
        xhr.open('get','http://localhost:8000/json-server');
        //发送
        xhr.send();
        //事件绑定
        xhr.onreadystatechange=function(){
            if(xhr.readyState===4){
                if(xhr.status===200){
                    console.log(xhr.response);
                    result.innerHTML=xhr.response;
                }
            }
        }
    }
</script>

在这里插入图片描述

数据转化

1.手动转化

   xhr.onreadystatechange=function(){
            if(xhr.readyState===4){
                if(xhr.status===200){
                    // 手动对数据转化
                    let data=JSON.parse(xhr.response);
                    console.log(data);
                    result.innerHTML=data.name;
                    //name值显示在div中
                }
            }
        }
    }

在这里插入图片描述
2.自动转化

 // 设置响应体数据的类型
xhr.responseType='json';

xhr.onreadystatechange=function(){
            if(xhr.readyState===4){
                if(xhr.status===200){
                    //自动数据转化 借助对象的属性来设置
                    console.log(xhr.response);
                    result.innerHTML=xhr.response.name;
                }
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值