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>
  • 相关阅读:
    IOS-JSON数据解析
    IOS-APP发布资料收集
    IOS-webService
    ASP.NET MVC学习之路:模板页
    io流
    线程
    事件监听
    java基础面试题
    递归调用
    三目运算: x?y:z
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/13908641.html
Copyright © 2011-2022 走看看