0
点赞
收藏
分享

微信扫一扫

原生ajax

ZMXQQ233 2022-04-15 阅读 102
javaajax

启动服务器

  1.初始化 在项目右键,打开控制台

 
输入npm init --yes            做初始化                 (npm是node.js下的包管理工具)

2.安装express框架 输入npm i express  安装express框架



安装成功  可以用这个例子检验一下

https://gitee.com/rjgc1192/ajax/tree/master/   版本号是c08b98

 3.创建.js文件,作为服务器的配置

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

// 3.创建路由规划
// request 是对请求报文的封装
// response是对响应报文的封装
// 要在后面输入server才可访问http://localhost:8000/server
app.get('/server',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin','*');
    // 设置响应
    response.send('hello  express');
});
app.post('/server',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin','*');
    // 设置响应
    response.send('hello  express');
});
// 当开启端口时执行的函数
app.listen(8000,()=>{
    console.log("服务已经启动,8000端口监听中");
})

4.新建一个 .html

使用原生的ajax有四步,1.创建对象  2.初始化请求方法和url  3.发送    4.事件绑定 处理服务端返回的结果

<!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>
    <style>
        #response{
        width: 200px;
        height: 200px;
        border: 1px solid red;
        }
    </style>

</head>
<body>
    <button id="btn">点我提交</button>
    <div id="response">返回值</div>
    <a href="http://127.0.0.1:8000/server">点我提交</a>
    <form action="http://127.0.0.1:8000/server" method="post">
        <input type="text" name="name1">
        <button type="submit">提交</button>
    </form>
</body>
</html>
<script>
 
    btn.onclick=function(){
    // 1.创建对象
    const xhr=new XMLHttpRequest();
    const test=document.getElementById("response");
    // 2.初始化请求方法和url
    xhr.open('GET','http://127.0.0.1:8000/server?a=10&b=100');
    // 3.发送
    xhr.send();
    // 4.时间绑定 处理服务端返回的结果
    // on   当什么..的时候
    // readystate  是xml对象中的属性,表示状态 0 1 2 3 4
    // 0 未初始化  
    // 1 open方法调用完毕  
    // 2 send方法调用完毕  
    // 3 服务端返回了部分结果 
    // 4 服务端返回了所有结果
    xhr.onreadystatechange=function()
    
    { //判断 (服务端是否返回了所有的结果)
        if(xhr.readyState===4)
        {
            
            // 成功访问该页面(状态码是200-300)
            if(xhr.status>=200 &&xhr.status<300)
            {//获得 状态码  状态字符串 响应头  响应体
                console.log(xhr.status);//输出状态码
                console.log(xhr.statusText);//获取状态字符串4
                console.log(xhr.getAllResponseHeaders);//所有的响应头
                console.log(xhr.response);//响应体
                test.innerHTML=xhr.response;
            }
        }
    }
    }
</script>

例子在gitee上,https://gitee.com/rjgc1192/ajax/tree/master/

版本号是 2345542

举报

相关推荐

0 条评论