jQ中的Ajax

152 阅读1分钟

1. HTTP协议-get和post的区别

image.png

2. $.ajax

image.png

<body>
    <button>登录</button>
    <h1></h1>
    <script src="./jquery-1.12.4.js"></script>
    <script>
        $('button').click(function () {
            $.ajax({
                url: "./login1.txt",
                method: 'get',
                async: true,
                dataType: 'json',
                success: function (res) {
                    console.log(res);
                    $('h1').html(`姓名:${res.name},${res.msg}`)
                    $('button').fadeOut('slow')
                },
                error: function () {
                    $('h1').html('请求失败')
                }
            })
        })
    </script>
</body>

3. $.get

<script>
        $('button').click(function () {
            // 参数:第一个是接口地址 第二个传输的数据 第三个是成功后的回调函数 
            $.get('./login.txt', { name: 'zhangsan', age: 30 }, function (data) {
                let res = JSON.parse(data)
                $('h1').html(`姓名:${res.name},${res.msg}`)
                $('button').fadeOut('slow')
            })
           // 参数:第一个是接口地址 第二个回调函数 
            /* $.get('./login.txt?name=zhangsan&age=30', function (data) {
                let res = JSON.parse(data)
                $('h1').html(`姓名:${res.name},${res.msg}`)
                $('button').fadeOut('slow')
            }) */
        })
    </script>

4. $.post

<body>
    <button>登录</button>
    <script src="./jquery-1.12.4.js"></script>
    <script>
        $('button').click(function () {
            // $.ajax({
            //     url: "http://timemeetyou.com:8889/api/private/v1/login",
            //     method: "post",
            //     data: {
            //         username: 'admin',
            //         password: '123456'
            //     },
            //     dataType: 'json',
            //     success: function (res) {
            //         console.log(res);
            //     },
            // })
            let url = "http://timemeetyou.com:8889/api/private/v1/login";
            /* $.post有三个参数 第一参数表示接口地址 第二个参数表示传输的数据 
            第三个参数表示成功后的回调函数 */
            $.post(url, { username: 'admin', password: '123456' }, function (res) {
                console.log(res);
            })
        })
    </script>
</body>

5. 跨域

看到报错信息中有Access to XMLHttpRequest by CORS policy: No 'Access-Control-Allow-Origin' 这些关键字,就代表是跨域错误。

产生跨域的原因

由浏览器的同源策略造成的。
同域名,同端口,同协议(http 和 https)

跨域解决方案

方案描述
CORS跨域资源共享服务端:header("Access-Control-Allow-Origin:*")
*”表示所有的域都可以接受
jsonp动态创建script标签,使用jQuery的jsonp请求
优点:兼容性强&不受同源策略的限制。
缺点:只能用get方法,不能使用post方法。