zoukankan      html  css  js  c++  java
  • node 与 Ajax 的等待响应

    // app.js
    
    const http = require('http');
    const fs = require('fs');
    
    let server = http.createServer();
    
    server.on('request', (req, res)=>{
        if(req.url === '/'){
            fs.readFile('./index.html', (err, data)=>{
                res.writeHead(200,{'content-type':'text/html;charset=utf-8'});
                res.end(data);
            })
        }else if(req.url === '/test' && req.method ==='GET'){
            res.writeHead(200,{'content-type':'application/octet-stream'});
            setInterval(function() {
                res.write(''+ Date.now()+ '^_^');
            },1000);
        }
    
        req.on('data', (data)=>{
            console.log(data.toString());
        })
    });
    
    server.listen(9999, ()=>{
        console.log('服务器9999 已开启');
    })
    <!-- index.html -->
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <span id='info'></span>
        <button id='btn'>点我发</button>
    </body>
    <script>
        var info = document.querySelector('#info');
        document.querySelector('#btn').onclick = function(){
            var xhr = new XMLHttpRequest();
            xhr.open('get', '/test');
            xhr.send();
            xhr.onreadystatechange = function(){
                console.log(xhr.readyState); //1,2,3,4
                console.log(xhr.responseText);
                var arr = xhr.responseText.split('^_^')
                console.log(arr[arr.length-2]);
                info.innerText = arr[arr.length-2];
            }
        }
    </script>
    </html>
  • 相关阅读:
    Linux下C程序插入执行shell脚本
    #ifdef预编译相关用法
    LAMP开发之环境搭建(2014.12.7在ubuntu下)
    Qt在VS2010的安装与配置
    vs2010配备boost编程环境
    Ubuntu虚拟机与Window、Arm的通信
    大小端测试程序
    Ubuntu安装google Gtest
    设计模式之单例模式
    设计模式之原型模式
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/13908641.html
Copyright © 2011-2022 走看看