AjAx的使用

89 阅读1分钟

AjAx的使用

 
<!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>GET方法</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border:1px solid #90b;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    <script>
        var btn = document.querySelector("button");
        var result = document.querySelector("#result");
        //绑定事件
      btn.onclick = function(){          
        //ajax的操作步骤
        //1.创建对象
        const xhr = new XMLHttpRequest();
        //2.设置请求的方法和url
        //设置url的方式 加?a=100&&b=200&&c=300
        xhr.open('GET','http://127.0.0.1:8000/server');
        //3.发送
        xhr.send();
        //4.处理服务器返回的结果
        /*readystate 是xhr对象中的属性 表示状态 
        0(未初始化) 
        1(open方法调用完毕) 
        2(send方法调用完毕) 
        3(表示服务端返回了不同的结果) 
        4 (表示服务端返回的所有结果)
        */
        xhr.onreadystatechange = function(){
          //判断 服务端 返回了所有的结果
          if(xhr.readyState === 4){
              //判断响应的状态码
              if(xhr.status >=200 && xhr.status < 300){
                //处理结果
                // console.log(xhr.status);//xhr.status保存了响应状态码 ====>200
                // console.log(xhr.statusText);//响应状态字符串 OK
                // console.log(xhr.getAllResponseHeaders());//所有的响应头==> content-length: 10
                // console.log(xhr.response);//响应体 ==>content-type: text/html; charset=utf-8
 
                result.innerHTML = xhr.response;
              }
          }
        }
        };
    </script>
</body>
</html>
 
 
 
//要想使用Ajax就引入Express框架
// Express的使用
// (1)引入Express
const express = require('express');
 
// (2)创建应用对象
const app = express();
 
// (3)创建路由规则
//request 是对请求报文的封装
//respanse 是对响应报文的封装
// 设置 GET
app.get('/server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
    //设置响应
    response.send('HELLO AJAX');
})