网络请求fetchs ajax 模拟数据(node 响应数据) -原生

ajax GET请求XML内容

     function ajax() {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://ysch-user.oss-cn-shenzhen.aliyuncs.com/')
            xhr.send();
            xhr.onreadystatechange = function (e) {
                //判断服务端 返回的所有的结果
                if (xhr.readyState === 4) {
                    //状态码 200~300之间都是成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // console.log(xhr.response) // json 格式
                        // console.log(xhr.responseText); // 文本 格式
                        // console.log(xhr.responseXML)  // xml 格式
                        let dom = xhr.responseXML
                        let xmlRoot = dom.documentElement;
                        // console.log(dom, '==dom')
                        // console.log(xmlRoot, '==xmlRoot')

                        let Name = xmlRoot.getElementsByTagName("Name");
                        let Key = xmlRoot.getElementsByTagName("Key");
                        console.log(Name[0], '==Name');
                        // console.log(Key, '==Key')
                        let arr = ''
                        for (let i = 0; i < Key.length; i++) {
                            // arr.push(Key[i].baseURI + Key[i].innerHTML)
                            arr += `<img src=${Key[i].baseURI + Key[i].innerHTML}>`

                        }
                        document.body.innerHTML = arr


                    }
                }
            }

        }
        ajax()

ajax post请求的XML内容

   function ajaxPost() {
            let xhr = new XMLHttpRequest();
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.open('POST', 'https://ysch-user.oss-cn-shenzhen.aliyuncs.com/')
            // xhr.send('name=zs&age=18');  // json模式
            // xml请求模式
            var xml = "<user><name>" + name + "</name><age>" + age + "</age></user>";
            xhr.send(xml);
            xhr.onreadystatechange = function (e) {
                //判断服务端 返回的所有的结果
                if (xhr.readyState === 4) {
                    //状态码 200~300之间都是成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // console.log(xhr.response) // json 格式
                        // console.log(xhr.responseText); // 文本 格式
                        // console.log(xhr.responseXML)  // xml 格式
                        let dom = xhr.responseXML
                        let xmlRoot = dom.documentElement;
                        // console.log(dom, '==dom')
                        // console.log(xmlRoot, '==xmlRoot')

                        let Name = xmlRoot.getElementsByTagName("Name");
                        let Key = xmlRoot.getElementsByTagName("Key");
                        console.log(Name[0].innerHTML, '==Name');
                        // console.log(Key, '==Key')
                        let arr = ''
                        for (let i = 0; i < Key.length; i++) {
                            // arr.push(Key[i].baseURI + Key[i].innerHTML)
                            arr += `<img src=${Key[i].baseURI + Key[i].innerHTML}>`

                        }
                        document.body.innerHTML = arr
                    }
                }
            }

        }

原生ajax get

     const xhr = new XMLHttpRequest()
     //设置请求方法和url
     xhr.open('GET', 'http://127.0.0.1:8888/server?username=ding&password=123456')
                //发送
                xhr.send()
                //处理服务端返回的结果
                /**
                 *XMLHttpRequest.readyState 属性返回一个 XMLHttpRequest  代理当前所处的状态
                 值    状态    描述
                 0    UNSENT    代理被创建,但尚未调用 open() 方法。
                 1    OPENED    open() 方法已经被调用。
                 2    HEADERS_RECEIVED    send() 方法已经被调用,并且头部和状态已经可获得。
                 3    LOADING    下载中; responseText 属性已经包含部分数据。
                 4    DONE    下载操作已完成。
                 */
                xhr.onreadystatechange = function () {
                    //判断服务端 返回的所有的结果
                    if (xhr.readyState === 4) {
                        //状态码 200~300之间都是成功
                        if (xhr.status >= 200 && xhr.status < 300) {
                            console.log(xhr.responseText);
                         }
                  }
                  }



原生post

 document.querySelector("#btnAjax").onclick = function () {
        var ajax = new XMLHttpRequest();
 
        // 使用post请求
        ajax.open('post','ajax_post.php');
 
        // 如果 使用post发送数据 必须 设置 如下内容
        // 修改了 发送给 服务器的 请求报文的 内容
        // 如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:
        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        // 发送
        // post请求 发送的数据 写在 send方法中
        // 格式 name=jack&age=18 字符串的格式
        ajax.send('name=jack&age=998');
 
        // 注册事件
        ajax.onreadystatechange = function () {
            if (ajax.readyState==4&&ajax.status==200) {
                console.log(ajax.responseText);
            }
        }
    }

php 后台

<?php
    // 获取 post的数据
    echo '你'.$_POST['age'].'岁了';
 ?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
    <button onclick="fetchs()">fetch网路请求</button>
    <script>
        //https://developer.mozilla.org/en-US/docs/Web/API/Response
        function fetchs() {
            fetch("https://dev.kemean.net/daiken/api/common/lunbo?locatType=1101")
                .then(response => response.json())
                .then(data => {
                    // data就是我们请求的repos
                    console.log(data)
                });
        }
    </script>
</body>

</html>

1.json文件

.json 按ajax传输 获取数据  // vue 传输是 json 路径在src 文件夹下
 
 vue 2.0 是在static 文件下
 vue 3.0public 文件下

2.js文件代替

3.mock

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>
    <script>
        var xhr = new XMLHttpRequest();
        xhr.open('get', encodeURI(url), ture)//加密 get有缓存加时间戳
        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.staus == 200) {
                    console.log(xhr.responseText);
                } else {
                    console.log(xhr.status)
                }
            }
        }

        //  var xhr=null
        //try{
        //    xhr=new XMLHttpRequest();
        //    }catch(e){
        //    xhr=new ActiveXObject("Microsoft.XMLHTTP");
        //    }
        //    //2.调用open方法(true----异步)
        //    xhr.open("post","links/2.post.php",true);
        //    //3.发送数据
        //    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
            //xhr.send("username="+userval+"&age="+ageval+"&timp"+new //Date().getTime());
            //4.请求状态改变事件
           // xhr.onreadystatechange=function(){
            //    if(xhr.readyState==4){
           //         if(xhr.status==200){
          //          document.write(xhr.responseText)
         //           }else{
         //           alert("错误"+xhr.status)
         //           }
         //       }
         //   }



        decodeURI(url)//解码
         //路径对加密解密函数
        // js对文字进行编码涉及3个函数:escape, encodeURI, encodeURIComponent,相应3个解码函数:unescape, decodeURI, decodeURIComponent

        //函数缺点
        // escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z
        // encodeURI不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z
        // encodeURIComponent不编码字符有71个:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

        // unescape 方法
        // 从用 escape 方法编码的 String 对象中返回已解码的字符串。
        // function unescape(charString: String): String
        // 参数
        // charString
        // 必选。要解码的 String 对象或文本。
        // 备注
        // unescape 方法返回一个包含 charstring 内容的字符串值。所有以 % xx 十六进制形式编码的字符都用 ASCII 字符集当中等效的字符代替。以 % uxxxx 格式(Unicode 字符)编码的字符用十六进制编码 xxxx 的 Unicode 字符代替。注意 unescape 方法不应用于解码“统一资源标识符”(URI) 。请改用 decodeURI 和 decodeURIComponent 方法。



        // decodeURI 方法
        // 返回一个已编码的统一资源标识符(URI) 的非编码形式。
        // function decodeURI(URIstring: String): String
        // 参数
        // URIstring
        // 必选。表示编码 URI 的字符串。
        // 备注
        // 使用 decodeURI 方法代替已经过时的 unescape 方法。
        // decodeURI 方法返回一个字符串值。
        // 如果 URIString 无效,将发生 URIError。



        // decodeURIComponent 方法
        // 返回统一资源标识符(URI) 的一个已编码组件的非编码形式。
        // function decodeURIComponent(encodedURIString: String): String
        // 必选的 encodedURIString 参数是一个表示已编码的 URI 组件的值。
        // 备注
        // URIComponent 是一个完整的 URI 的一部分
    </script>
</body>

</html>
window.addEventListener('unload', logData, false);

function logData() {
    var client = new XMLHttpRequest();
    client.open("POST", "/log", false); // 第三个参数表明是同步的 xhr
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(analyticsData);
}
window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}

参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/sendBeacon

axiso:http://www.axios-js.com/
//前端

<!DOCTYPE html>
<html lang="ch">
    <head>
        <meta charset="UTF-8">
        <title>使用原生的ajax发送get请求</title>
        <style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }

            #result {
                width: 500px;
                height: 130px;
                border: 1px solid red;
            }
        </style>
    </head>
    <body>
        <button>点我发送请求</button>
        <div id="result"></div>
        <script type="text/javascript">
            //获取button
            let button = document.getElementsByTagName('button')[0]
            //获取id为result的那个div
            let result = document.getElementById('result')
            //绑定一个点击事件
            //弄不清这些看mdn文档:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest
            button.onclick = function () {
                //创建XMLHttpRequest对象
                const xhr = new XMLHttpRequest()
                //设置请求方法和url
                xhr.open('GET', 'http://127.0.0.1:8888/server?username=ding&password=123456')
                //发送
                xhr.send()
                //处理服务端返回的结果
                /**
                 *XMLHttpRequest.readyState 属性返回一个 XMLHttpRequest  代理当前所处的状态
                 值    状态    描述
                 0    UNSENT    代理被创建,但尚未调用 open() 方法。
                 1    OPENED    open() 方法已经被调用。
                 2    HEADERS_RECEIVED    send() 方法已经被调用,并且头部和状态已经可获得。
                 3    LOADING    下载中; responseText 属性已经包含部分数据。
                 4    DONE    下载操作已完成。
                 */
                xhr.onreadystatechange = function () {
                    //判断服务端 返回的所有的结果
                    if (xhr.readyState === 4) {
                        //状态码 200~300之间都是成功
                        if (xhr.status >= 200 && xhr.status < 300) {
                            //success
                            //处理结果 报文(行 头 空行 体)
                            let status = xhr.status //状态码
                            let statusText = xhr.statusText //状态字符串
                            let arh = xhr.getAllResponseHeaders() //所有响应头
                            let response = xhr.response //响应体
                            //设置id为result的那个div的响应文本
                            result.innerHTML = 'status:' + status + '<br/>statusText:' + statusText +
                                '<br/>AllResponseHeaders:' + arh + '<br/>response:' + response
                        } else {
                            console.log('server error')
                        }
                    }
                }
            }
        </script>
    </body>
</html>

node 响应数据

// 后台

//引入express
const express = require('express')
//端口号
const port = 8888
//创建应用对象
const app = express()

//创建路由规则 路由就是引路人 根据不同的url请求 导航到不同的页面
app.get('/server', (request, response) => {
    //request 是对请求报文的封装
    //response 是对响应报文的封装
    //设置响应头 允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*')
    //设置响应体
    response.send('Hello Ajax,I am dingqiusi->get')
})
//监听端口 启动服务
app.listen(port, () => {
    console.log(`服务已经启动了,端口号:${port}`)
})

// fs.readFile("./1.json", "utf8", function (err, data) {
//   //   let str = data.trim().replace(/\s+/g, "");
//   function Trim(str, is_global = "i") {
//     var result;
//     result = str.replace(/(^\s+)|(\s+$)/g, "");
//     if (is_global.toLowerCase() == "g") result = result.replace(/\s/g, "");
//     return result;
//   }

//   fs.writeFile("./11.json", Trim(data, "g"), function (err) {
//     if (err) console.log("写文件操作失败");
//     else console.log("写文件操作成功");
//   });
//   //   console.log(Trim(data, "g"));
// });

// var data = fs.readFileSync("./test.txt", "utf8");
// console.log(data);

var http = require("http");
// req 路由监听空 res 上下文函数
var server = http.createServer((req, res) => {
  // 公共请求头
  res.writeHead(200, {
    "Content-Type": "text/html;chaset=UTF-8",
    //设置允许跨域的域名,*代表允许任意域名跨域
    "Access-Control-Allow-Origin": "*",
  });

  // 路由监控
  if (req.url == "/fang") {
    res.end("fang");
  } else if (req.url == "/yuan") {
    res.end("yuan");
  } else {
    // res.end("404");
    res.end("<a href='/fang'>fang</a><br><a href='yuan'>yuan</a>");
  }
});
server.listen(3000, "127.0.0.1", () => {
  console.log("http://127.0.0.1:3000/");
});

// var http = require("http");

// var server = http.createServer(function (req, res) {
//   if (req.url !== "/favicon.ico") {
//     res.writeHead(200, {
//       "Content-Type": "text/plain",
//       "Access-Control-Allow-Origin": "*",
//     });

//     res.write("你好啊!");
//   }

//   res.end();
// });

// server.listen(1337, "localhost", function () {
//   console.log("开始监听...");
// });

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

web修理工

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

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

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

打赏作者

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

抵扣说明:

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

余额充值