day23-Ajax

Ajax介绍

  • Ajax=Async JavaScript and XML(异步的JavaScript 和 XML)
  • 概念:Ajax不是新的编程语言,而是一个异步的用于发送 http 请求的技术
  • Ajax特点:
    • 无需刷新页面,可以更改页面布局内容
    • 按需加载,减轻服务器的压力
    • 实时更新
    • 提供用户体验

Ajax使用步骤

【1】创建Ajax的对象
【2】设置请求方式和接口地址

  • 在Ajax对象中 ,有一个open()的方法用于设置请求方式和地址
  • 第三参数:设置同步或者异步 取值为布尔值。默认情况下为true,表示异步。false表示同步
  • 同步:代码会从上到下一步一步执行
  • 异步:Ajax请求,定时器,当程序遇到异步代码的时候,异步代码后面的同步代码不会等待异步代码执行之后再去执行(同步代码会先执行)

【3】发送请求

  • 在Ajax对象中有一个send()方法 用于发送请求

【4】获取服务端响应的数据(拿到后端返回的数据)

  • 如果Ajax请求是一个异步请求 readState 为 Ajax请求的状态码

    • 0 表示Ajax初始化
    • 1 表示设置了请求方式和地址
    • 2 客户端向服务端发送成功
    • 3 服务端响应数据 但是还没处理完成
    • 4 表示数据处理完成 ,可以正常使用
  • status 为 http 请求的状态

    • status == 200
 xhr.onload  = funciton(){ }

(1)onreadystatechange事件
(2)ajax 状态码

xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
    }
 }

(3)接收服务器返回的数据:responseText 存储服务端返回的响应体

xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
   		console.log(xmlhttp.responseText)
    }
 }

Ajax演示

【1】get请求
  1. ajax_get.html
<!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>Document</title>
    </head>
    <body>
        <form action="">
            <p>
                <label for="">用户名:</label>
                <input type="text" id="username" name="username" />
            </p>
            <p>
                <label for="">密码:</label>
                <input type="text" id="password" name="password" />
            </p>

            <button id="btn">登录</button>
        </form>

        <script>
            let btn = document.querySelector("#btn");
            let form = document.querySelector("form");
            let username = document.querySelector("#username");
            let password = document.querySelector("#password");

            // form 表单的提交事件
            // form表单提交事件 有一个默认行为 自动刷新浏览器
            // 怎么实现不刷新浏览器,阻止浏览器的默认行为
            form.onsubmit = function () {
                let e = window.event;
                // e.preventDefault();
                e.returnValue = false;
                let xhr = new XMLHttpRequest();
                // 需要给 请求传递参数
                // get请求的参数 直接写在  接口的后面,用?连接起来
                // 参数格式:key=value&key=value
                // xhr.open("get", "./login.php?username="+username.value+"&password="+password.value);

                xhr.open(
                    "get",
                    `./login.php?username=${username.value}&password=${password.value}`
                );
                xhr.send();

                xhr.onload = function () {
                    // console.log(xhr.responseText);
                    // 获取的值 一般是json数据
                    // 需要把json数据转化为js数据
                    // JSON.parse() 把json数据转化为js数据
                    // JSON.stringify()
                    let res = JSON.parse(xhr.responseText);

                    // 判断是否登录成功 res.code == true 的时候表示登录成功
                    if (res.code) {
                        location.href = "./car.html";
                    } else {
                        alert(res.msg);
                    }
                };
            };
        </script>
    </body>
</html>

  1. login.php
<?php

    // echo '123';
    $user = $_GET['username'];
    $pass = $_GET['password'];

    $con = mysqli_connect('localhost','root','123456','login');

     $sql = "SELECT * FROM `user` WHERE `username`='$user' AND `password`='$pass'" ;

    $res = mysqli_query($con,$sql);


    if(!$res){
     
        die('数据查询错误' . mysqli_error($con));
    }

    $row = mysqli_fetch_assoc($res);
    

    if($row){
        $arr = array('code'=>true,'msg'=>'登录成功');
        print_r(json_encode($arr,JSON_UNESCAPED_UNICODE));
        // 表示登录成功 跳转到list页面
    }else{
        $arr = array('code'=>false,'msg'=>'用户名或者密码错误');
        print_r(json_encode($arr,JSON_UNESCAPED_UNICODE));
    }
?>
  1. car.html(如果Ajax请求数据库成功,将会跳转car页面)
<!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>Document</title>
    </head>
    <body>
        我是购物车页面
    </body>
</html>

post请求
  1. ajax_post.html
<!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>Document</title>
    </head>
    <body>
        <form action="">
            <p>
                <label for="">用户名:</label>
                <input type="text" id="username" name="username" />
            </p>
            <p>
                <label for="">密码:</label>
                <input type="text" id="password" name="password" />
            </p>

            <button id="btn">登录</button>
        </form>

        <script>
            let btn = document.querySelector("#btn");
            let form = document.querySelector("form");
            let username = document.querySelector("#username");
            let password = document.querySelector("#password");

            form.onsubmit = function () {
                let e = window.event;
                e.returnValue = false;

                let xhr = new XMLHttpRequest();

                xhr.open("post", "./login_post.php");
                // post 请求的参数 放在请求体中
                // 在传递的时候 写在send中
                // 当用post请求携带参数的时候 需要给请求头设置 请求参数的格式
                xhr.setRequestHeader(
                    "Content-Type",
                    "application/x-www-form-urlencoded"
                );
                xhr.send(
                    `username=${username.value}&password=${password.value}`
                );

                xhr.onload = function () {
                    // console.log(xhr.responseText);
                    let res = JSON.parse(xhr.responseText);
                    if (!res.code) {
                        alert(res.msg);
                        return;
                    }
                    location.href = "./car.html";
                };
            };
        </script>
    </body>
</html>

cookie演示

在这里插入图片描述

  1. cookieTest.html
<!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>Document</title>
        <script src="../cookie.js"></script>
    </head>
    <body>
        <button id="btn">退出登录</button>
        <script>
            setCookie("login", 1, 5);
            setCookie("name", "aaa", 5);
            // setCookie();

            // let res = getCookie("login");
            // let res = getCookie();

            let btn = document.querySelector("#btn");
            btn.onclick = function () {
                // console.log(1);
                // 删除cookie:设置过期时间 为当前时间之前
                // 只要过期时间设置为负数就表示删除cookie
                setCookie("login", "1", -1);
            };
        </script>
    </body>
</html>
  1. cookie.js
//  获取cookie
// 传递一个参数,这个参数为 cookie的 key
// 返回值:cookie中这个key对应值
// 如果没有传递 attr cookie的key的时候
// 返回所有的cookie
function getCookie(attr) {
    // name=aaa; age=18
    let res = document.cookie;
    // {name:'aaa',age:18}
    let obj = {};
    let arr = res.split("; ");

    arr.forEach((item) => {
        let array = item.split("=");
        obj[array[0]] = array[1];
    });

    if (attr) {
        return obj[attr];
    }
    return obj;
}

// 设置cookie
// 参数:
// key:cookie中name 必填
// value key的值 必填
// expires:过期时间,可选,单位为分钟
function setCookie(key, value, expires) {
    if (!key || !value) {
        // 手动抛出一个错误
        throw Error("参数1和参数2是必填");
    }

    // path=/ 表示这个cookie设置在 这个域名的根目录下面
    if (!expires) {
        document.cookie = `${key}=${value};path=/`;
        return;
    }

    let date = new Date();
    let time = date.getTime() - 8 * 60 * 60 * 1000 + expires * 60 * 1000;
    date.setTime(time);
    document.cookie = `${key}=${value};expires=${date};path=/`;
}

同源策略

  • 同源策略:浏览器提供的一个网络安全的协议
  • 当端口,域名或者协议不同的时候,就表示触发了同源策略
  • 触发了同源策略的请求 被称之为 跨域请求,跨域请求一般请求不到数据
  • 解决跨域请求:【1】jsonp(利用script标签) 【2】反向代理
  • 在HTML中有一些标签不受同源策略的影响
    • img
    • script
    • link
    • iframe
//例如在http://gz2101.com/day03_code/jsonp/01_jsonp.html打开别的网址

<img src="http://jsonp.io/jsonp.php" alt="">

<!--
                把你要请求的接口 直接写在script的src属性上
                需要传递一个参数 cb || callback
                这个参数的值 为一个已经存在的函数的名字
 -->
<script src="http://jsonp.io/jsonp.php?cb=fun"></script>
  • jsonp.html
<!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>Document</title>
    </head>
    <body>
        <button id="btn">点击请求数据</button>

        <script>
            function fun(res) {
                console.log(res);
            }

            let btn = document.querySelector("#btn");
            btn.onclick = function () {
                //动态创建 script标签
                let script = document.createElement("script");

                script.setAttribute("src", "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=40020637_7_oem_dg&wd=iframe&fenlei=256&rsv_pq=e014c205000f682a&rsv_t=90319eYkI528xUYmrurYbkL3FMxG33Yy2w1oNTDVvVwgxJkMi21ATDCh1B9pbzgbDOIIYW3z%2BJo&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=8&rsv_sug1=7&rsv_sug7=101&rsv_sug2=0&rsv_btype=i&prefixsug=iframe&rsp=5&inputT=1518&rsv_sug4=2002");
                document.body.appendChild(script);

                // 获取到数据之后 需要把这个标签移出
                script.remove();
            };
        </script>

        <!-- 表示浏览器一打开的时候 就马上执行 数据的获取 -->
        <!-- <script src="http://jsonp.io/jsonp.php?cb=fun"></script> -->
    </body>
</html>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值