JavaScript基础语法七

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示:这里可以添加本文要记录的大概内容:

jquery、ajax、axios基本了解


提示:以下是本篇文章正文内容,下面案例可供参考

一、jquery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery.min.js"></script>
    <script>
        $(function (){
            console.log("九黎,我爱你");
        });
        // $(函数); // 固定逻辑,表示当页面加载完毕后,要去执行的函数
        // 相当于 window.onload = function (){console.log("九黎,我爱你");}
        window.onload = function (){console.log("九黎,我爱你");}

        // $() => jquery选择器 ->返回的是jquery对象.你可以虽然使用jquery中的各种功能
        // document.querySelector() => 通过选择器选择页面上的内容 ->返回的是dom对象 -> $(dom对象)

        // 功能上来将一样,jquery代码少
        //绑定事件,当按钮被点击的时候.输出一句话
        window.onload = function (){
            document.querySelector("#btn_dom").addEventListener("click",function(){
                console.log("原生js->点击你");
            })
        }
        $(function(){
            $("#btn_jquery").click(function (){
               console.log("jquery -> 点击你");
            });
        })

        function fn(){
            // 获取数据
            var txt = $("div").text();// 拿到文本
            var hm = $("div").html(); // 拿到html
            console.log(txt);
            console.log(hm);

            // 给标签设置数据
            // 向div中写入文本内容
            // $("div").text("灵儿");
            // $("div").html("<input type='text' />")

            // document.querySeletor(#jj).value = "xxx"
            // $("#jj").val("九黎,我爱你"); //设置value属性值
            // console.log($("#jj").val());

            // jquery $(xxxx).val() text() html()
            // 不传参 拿数据
            // 传参 放数据

            // 获取数据 $("span").attr(key);
            // var a = $("span").attr("jl");
            // console.log(a);
            // 设置属性值 $("span").attr(key,value)
            // $("span").attr("jl","ler");

        }
    </script>
</head>
<body>
<input type="button" value="普通按钮" id="btn_dom">
<input type="button" value="jquery按钮" id="btn_jquery">
<input type="button" value="点我" onclick="fn();">
<hr>
<div>
    <span jl="九黎">九黎,我爱你</span>
    <input type="text" name="" id="jj">
</div>
</body>
</html>

二、ajax

js原生的 ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // 原生的js ajax请求
    </script>
</head>
<body>
    <button id="btn">点我,给我服务器发送消息</button>
    <script>
        // 如果自己写的函数。是很容易通过调用栈,找到的(逆向的时候能看到)
        // hook open -> 由于open是系统寒霜,这种自带的寒霜到了send()
        // 被hook的open是看不到的...
        var _XMLHttpRequest_open = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function(method,url){
            url += "?p=10086"; // 模拟加密
            return _XMLHttpRequest_open.call(this,method,url);
        }
        // 破局在console输入命令,看XMLHttpRequest.prototype.open是否正常 ƒ open() { [native code] }正常 否则就是被hook修改了
        // open send
    </script>
    <script>
        // 原生的js ajax请求
        document.querySelector("#btn").addEventListener("click",function(){
            console.log("走你");
            // 创建xhr对象
            var xhr = new XMLHttpRequest();
            // 2. open -> url
            xhr.open("get","/ajax_01");
            // 2.5 设置返回值如何接收
            xhr.onreadystatechange = function (){
                // 服务器返回了东西,并且,返回的东西已经全部接收到
                if(xhr.readyState == 4){
                    if(xhr.status === 200){
                        // 服务器返回的数据
                        var data = xhr.responseText;
                        console.log("====>",data)
                        var div = document.createElement("div");
                        div.innerText = "hello";
                        document.querySelector("body").append(div);
                    }

                }
            }
            // 3. 发请求
            xhr.send("post请求的参数");//发请求
            // 接受服务器返回的东西
        });
    </script>
</body>
</html>

jquery的ajax get

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/js/jquery.min.js"></script>
</head>
<body>
    <button id="btn">点我,给我服务器发送消息</button>
    <script>
        var _XmlHttpRequest_open = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function (method, url){
            url += "&jl=10086";
            return _XmlHttpRequest_open.call(this, method, url);
        }
    </script>
    <script>
        $("#btn").click(function(){
            // $.get();// get请求
            // $.post(); // post
            // 用jquery发送ajax
            $.ajax({
                url: "/get_ajax_jquery?username=jl", // url地址
                method: "get", // 请求方式
                success: function(resp){ // 请求正常返回后,要干什么
                    console.log("服务器返回的数据是:",resp)
                }
            });
            // js能发请求的只有ajax
            // var xhr = new XmlHttpRequest();
            // xhr.open(method,url);
            // xhr.send();
            // 在往里挖就是浏览器源码(C语言)
        });
    </script>
</body>
</html>

jquery的ajax post

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/js/jquery.min.js"></script>
</head>
<body>
    <button id="btn">点我,给我服务器发送消息</button>
    <script>
        $("#btn").click(function(){
            // $.get();// get请求
            // $.post(); // post
            // 用jquery发送ajax
            $.ajax({
                url: "/get_ajax_jquery_post", // url地址
                method: "post", // 请求方式
                // 默认情况下.post的data对应的是form data
                // key=value&key=value&key=value... -> 固定的数据格式
                // requests模块内部会自动的把data处理成上面这个格式
                // requests.post(url, data={})
                // data:{ // 给post请求增加参数
                //     username:"寒霜",
                //     age: 18
                // },
                contentType: "application/json",
                data:JSON.stringify({'username': "hanshuang","age":18}),
                success: function(resp){ // 请求正常返回后,要干什么
                    console.log("服务器返回的数据是:",resp)
                }
            });
            // js能发请求的只有ajax
            // var xhr = new XmlHttpRequest();
            // xhr.open(method,url);
            // xhr.send();
            // 在往里挖就是浏览器源码(C语言)
        });
    </script>
</body>
</html>

三、axios

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/js/axios.min.js"></script>
    <script>
        // axios.get("/get_axios").then(function(rep){
        //     console.log(rep)
        //     return axios.post("/post_axios",{uname:"jiuli","age":18},{headers:{'token':10086}})
        // }).then(function(rep){
        //     console.log(rep)
        // }).catch(function(){
        //     console.log("有人兜底")
        // })

        // 查找加密/解码 -> 拦截器
        // 拦截器:为了让整个项目. 在不改动原有代码基础上.跨越随意的对请求和响应进行拦截
        // 一般用来做一些公共的任务(加密,解密)

        //请求拦截。此时,整个网站所有的axios请求都会被该拦截器拦器
        //自动的执行第一个函数
        // axios.interceptors.request.use(function (){请求发送要去做的事情},function (){})
        // //响应拦截。此时,整个网站所有的axios响应都会被该拦截器拦器
        // //自动的执行第一个函数
        // axios.interceptors.response.use(function (){响应回来之后要做的事情},function (){})
        axios.interceptors.request.use(function (config){
            console.log("我是请求拦截器,我发生在请求发送之前");
            //debugger;   // 断点的时候,抓包里面有没有东西
            console.log(config);
            return config; //要返回请求
        },function (){})

        axios.interceptors.response.use(function (resp){
            console.log("我是响应拦截器,请求回来之后,先执行这里,然后在执行后面的then");
            //debugger;   // 断点的时候,抓包里面有没有东西
            console.log(resp);
            return resp; //要返回请求
        },function (){})

        axios.get("/get_axios").then(function(rep){
            console.log("我是业务代码.处理响应")
        });
        // 请记住一个单词interceptors
    </script>
</head>
<body>

</body>
</html>

四、Python Flask服务代码

# Flask 后端服务器的开发
# pip install Flask = 2.1.3
# pip install Flask-Cors == 3.0.10
import json

from flask import Flask, render_template, request

app = Flask("jiuli")

# 编写函数,当请求发送过来之后,可以处理这个请求
# @app.route("/") 路由.表示有人访问/的时候,由jl_func_1来完成请求的处理
@app.route("/")
def jl_func_1():
    # 接受一些参数
    # args表示接收,url上面的?参数
    # http://xxx.xxx.com/s?username=xxx&pwd=xxx
    # uname = request.args.get("uname")
    # print("====>",uname)

    # 请求头:
    print(request.headers)
    ua = request.headers.get("User-Agent")
    print("===>",ua)
    if "python" in ua:
        return "滚"
    # 从服务器里查询出来的一篇文章
    article = "九黎,我爱你"
    # f = open("index.html",mode='r',encoding='utf-8')
    # content = f.read()
    # # 做一下替换
    # content = content.replace("{{ z }}",article)
    # return content

    # 模块渲染
    # render_template默认读取的是template文件夹
    # 读取index.html 替换掉wenzhang, 更换成article
    # 此时, 数据是在服务器端,放入html的 -> 服务器端渲染
    # 典型的: 豆瓣top250 -> 在抓包工具中能看到数据在页面源代码里
    # 请注意,如果没有ajax,页面上,超链接,form表单,这种东西
    # 在被点击的时候,向服务器发请求的逻辑,都是全页面刷新.
    return render_template("index.html",wenzhang=article)

# 为了防止出现跨域问题。直接从服务器进入页面
@app.route("/goto_ajax_01")
def goto_ajax_01():
    return render_template("ajax_01.html")

@app.route("/ajax_01")
def ajax_01():
    print("你好")
    return "九黎"

@app.route("/goto_ajax_02_jquery")
def goto_ajax_02_jquery():
    return render_template("ajax_02.html")

@app.route("/get_ajax_jquery")
def get_ajax_jquery():
    print("来了")
    uname = request.args.get("username")
    print(uname)
    return "你好"

@app.route("/goto_ajax_03_jquery")
def goto_ajax_03_jquery():
    return render_template("ajax_03.html")

# flask的路由默认只支持get. 想要支持post, methods = ['post']
@app.route("/get_ajax_jquery_post", methods=['post'])
def get_ajax_jquery_post():
    # request.args # url上面的参数
    # request.form # form data
    # print(request.form.get("username"))
    # print(request.form.get("age"))
    # print(request.form) # form
    print(request.json) # json
    return "hs"

@app.route("/get_jsonp")
def get_jsonp():
    cb = request.args.get("callback")
    obj = {
        "username":"jiuli",
        "age":18
    }
    return f'{cb}({json.dumps(obj)})' # callback(数据)

@app.route("/go_to_axios")
def go_to_axios():
    return render_template("03_axios.html")

@app.route("/get_axios")
def get_axios():
    print("访问axios")
    return "hello"

@app.route("/post_axios",methods=['post'])
def post_axios():
    print("访问post_axios")
    return "post_axios_return data"

if __name__ == '__main__':
    # debug=True 修改代码 会自动重启服务器
    app.run(host='127.0.0.1',port=12581,debug=True)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九丶黎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值