微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax学习笔记

ajax学习笔记

ajax的缺陷:

  • 没有浏览历史,不可退回;

  • SEO不友好;

  • 存在跨域问题;

Express框架:

安装:npm i express

//引入express
const express = require('express');
//创建应用对象
const app = express();
//创建路由规则
//request是对请求报文的封装
//response是对响应报文的封装
//get方法
app.get('/server',(request,response)=>{
    //设置响应头 设置允许跨域
    //第一个参数是名字,第二个参数是内容
    response.setHeader('A','*')
    //设置响应
    response.send('Hello Express');
})
//post方法
app.post('/server',(request,response)=>{
    //设置响应头 设置允许跨域
    //第一个参数是名字,第二个参数是内容
    response.setHeader('A','*')
    //设置响应
    response.send('Hello Express POST');
})
//监听端口服务器
//5500
app.listen(8000,()=>{
    console.log("服务器已启动,8000端口监听中....");
})
//代码更改后需要重新启动服务器

启动express脚本:

node 文件名.js

关闭端口:ctrl+c;

建立ajax-GET方法请求:

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <Meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax GET方法请求</title>
</head>
<body>
    <button>点我发送请求</button>
    <div class="result">
    </div>
    <script>
        //获取dom元素
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementsByClassname('resulte')[0];
        //绑定click事件;
        btn.onclick = function(){
            //创建对象
            const xhr =new XMLHttpRequest();
            //初始化 设置请求方法和url
            xhr.open('GET','http://192.168.1.102:8000/server');
            //url带参数的写法
            //xhr.open('GET','http://192.168.1.102:8000/server?a=100&b=200&c=300');
            //发送
            xhr.send();
            //事件绑定 处理服务端返回的结果
            //onreadystatechange 
            //readystate:属性的状态:0、1、2、3、4
            xhr.onreadystatechange = function(){
                //判断(readyState的值为4,则返回了所有的处理结果)
                if(xhr.readyState ===4){
                    //判断响应状态码(statu的值为200 ,则进行下一步)
                    //status ===2xx:成功
                    if(xhr.status >= 200 && xhr.status <300){
                        //处理结果
                        //响应行
                        console.log(xhr.status);//状态码
                        console.log( xhr.statusText);//状态字符串
                        console.log(xhr.getAllresponseHeader());//所有的响应头
                        console.log(xhr.response);//响应体
                        result.innerHTML = xhr .response;
                    }
                }
            }
        }
    </script>
</body>
</html>

建立ajax-POST方法请求:

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <Meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax-POST方法请求</title>
    <style>
        .result{
            width:100px;
            height:100px;
            border:1px solid red;
        }
    </style>
</head>
<body>
    <div class="result">
    </div>
    <script>
        const result= document.getElementsByClassName("result");
        //绑定事件
        result.addEventListener("mouSEOver",function(){
            const xhr = new HMLHttpRequest();
            xhr.open("POST",'http://192.168.1.102:8000/server');
            //设置请求头
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
            //post方式在send()里面设置参数,可以设置任何格式的数据
            xhr.send('a=100&&b=200&c=300');
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status >= 200 && xhr.status<300){
                        //处理服务端返回的结果
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>
</html>

获取json对象:

//服务器必须传递字符串类型的数据
//服务端
const data={
    name:'zhangxinxin'
};
let str = JSON.stringify(data);
response.send(str);
//开发端
//手动数据转换
let data = JSON.parse(xhr.response);
console.log(data);
//自动数据转换
xhr.responseType = 'json';
let data = xhr.response;
console.log(data);

为了调试服务端代码,安装:nodemon

npm i nodemon -g
//运行
nodemon 文件

解决ie浏览器缓存问题:

//加事件锉,
xhr.open("POST",'http://192.168.1.102:8000/server?t=' +Date.Now());

超时设置:

xhr.timeout = 2000;
xhr.ontimeout = function(){
    alert("网络异常,稍后重试")
}
//网络异常
xhr.onerror = function(){
    alert("你的网络似乎除了点问题")
}

请求取消:

//请求取消
xhr.abort(); 

重复发送请求:

let isSending = false;//通过控制布尔值来判断是否是在发送请求
btns[0].onclick =function(){
    if(isSending){
        xhr.abort();
    }//如果正在发送,则取消该请求,创建一个新的请求;
    xhr = newXMLHttpRequest();
     isSending=ture;
     xhr.open("GET",'http://192.168.1.102/server');
     xhr.send();
     xhr.onreadystatechange = function(){
        if(xhr.readyState ===4 ){
             isSending = false;
           }
       }
    
}

BootCDN:www.bootcdn.com

jQuery:

$('button').eq(0).click(function(){
    $.get('http:192.168.1.102:8000/server',{a:100,b:100},function(data){
        console.log(data);
    },)
})
//可以加第4个参数:"JSON"  数据转换为JSON格式
$('button').eq(1).click(function(){
    $.get('http:192.168.1.102:8000/server',{a:100,b:100},function(data){
        console.log(data);
    })
})
//ajax方法
$('button').eq(2).click(function(){
    $.ajax({
        url:'http:192.168.1.102/server',
        data:{a:100,b=200},
        type:'GET',
        dataType:'JSON',
        success:function(data){
            console.log(data);
        },
        //超时时间
        timeout:2000,
        //失败大的回调函数
        error:function(){
            console.log('出错啦!!!')
        },
        Headers:{
        }
    })
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐