Nodejs__代码__精简__Ajax交互

 简介 :

全称Ajax(Asynchronous Javascript And XML)
作用

1.不需要刷新页面即更新内容 

2.浏览器和服务器之间的一种通信方式


常用参数 :

XMLHttpRequest

一个构造函数,用于实现浏览器与服务器之间的异步通信

例子:let xhr=new XMLHttpRequest()

readyState

表示XMLHttpRequest的状态

0

未初始化,尚未调用open()

1

启动,已经调用open(),但尚未调用send()

2

发送,已经调用send(),但是尚未接收到响应

3

接收,已经接收到部分响应数据

4

完成,已经接收到全部响应的数据,而且已经可以在浏览器中使用

response

获得任意类型的响应数据

responseText

获得字符串类型的响应数据

responseType

设置响应数据的类型

timeout

设置请求超时时间,单位是ms

status

表示HTTP状态码,200 网页...ok

statusText

表示HTTP状态码说明

withCredentials

指定使用ajax发送请求时,是否携带cookie

open

设置请求的类型,URL以及是否异步处理请求

send

发送请求

abort

终止当前的请求

setRequestHeader

设置请求头信息,其中Content-type字段告诉服务器,数据格式

设置发送的数据是-表单默认的提交数据的格式:

例子:xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')

onreadystatechange

当readyState改变时,就会触发onreadystatechange事件


代码示例 : 

浏览器与服务器之间,进行简单的通信

 前端文件 :index.html

<!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>
  </head>

  <body>
    <h1>Ajax交互</h1>
    <button id="bt_get">Get测试</button>
    <button id="bt_post">Post测试</button>
    <script>
      const bt_get = document.getElementById("bt_get");
      const bt_post = document.getElementById("bt_post");
      var jx = {
        type: "POST",
        url: "http://127.0.0.1:80/",
        data: { name: "abc", move: "电影" },
        dataType: "json",
        async: true,
        success: function () {
          console.log("is ok...");
        },
        error: function () {
          alert("Error:非POST或GET请求");
        },
      };
      function paramGroup(data) {
        let arr = [];
        for (let i in data) {
          arr.push(i + "=" + data[i]);
        }
        return arr.join("&");
      }
      function ajaxFc(obj) {
        var xhr = null,
          str = paramGroup(obj.data);
        // 创建xhr
        if (window.XMLHttpRequest) {
          xhr = new XMLHttpRequest();
        } else {
          xhr = new ActiveXObject("Microsoft,XMLHTTP");
        }
        console.log(obj.type.toLowerCase());
        if (obj.type.toLowerCase() === "get" && obj.data !== undefined) {
          let url = obj.url + "?" + str;
          xhr.open(obj.type, url, obj.async || true);
          xhr.send(null);
        } else if (
          obj.type.toLowerCase() === "post" &&
          obj.data !== undefined
        ) {
          xhr.open(obj.type, obj.url, obj.async || true);
          xhr.setRequestHeader(
            "Content-type",
            "application/x-www-form-urlencoded"
          );
          xhr.send(str);
        } else {
          obj.error();
          return false;
        }
        // 事件绑定 处理服务端返回的结果
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            let res = xhr.responseText;
            try {
              if (typeof res === "object" || typeof res === "string") {
                alert(res);
              } else if (obj.dataType === "json") {
                console.log("json数据");
              } else {
                throw new Error();
              }
            } catch (e) {
              throw new Error();
            }
          }
        };
      }
      bt_get.onclick = function () {
        jx.type = "get";
        jx.url = "http://127.0.0.1:80/api/get";
        ajaxFc(jx);
      };
      bt_post.onclick = function () {
        jx.type = "post";
        jx.url = "http://127.0.0.1:80/api/post";
        ajaxFc(jx);
      };
    </script>
  </body>
</html>

 后端文件 :index.js

const express = require('express');
const e = express();
e.get('/api/get', (req, res) => {
    res.send('Get ....Ok');
});
e.post('/api/post', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.send('Post ....Ok');
});
e.listen(80, function () { 
    console.log('Server runing at 127:0.0.1:80'); 
}); 

 代码运行 

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

vip飞梦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值