单页面应用hash、history原理以及JSONP的分析

home.html文件

<body>
    <div>
        <button id=‘btn1‘>按钮1</button>
        <button id="btn2">按钮2</button>
    </div>
</body>
<script>
    const bindEventListener = function (type) {
        const historyEvent = history[type];
        return function () {
            const newEvent = historyEvent.apply(this, arguments);
            const e = new Event(type);
            e.arguments = arguments;
            window.dispatchEvent(e);
            return newEvent;
        };
    };
    history.pushState = bindEventListener(‘pushState‘);
    history.replaceState = bindEventListener(‘replaceState‘);
    window.addEventListener(‘replaceState‘, function (e) {
        console.log(‘THEY DID IT AGAIN! replaceState‘);
    });
    window.addEventListener(‘pushState‘, function (e) {
        console.log(‘THEY DID IT AGAIN! pushState‘);
    });

    document.addEventListener(‘popstate‘, (e) => {
        console.log(e, ‘popstate‘);
    })
    document.addEventListener(‘hashchange‘, (e) => {
        console.log(e, ‘hashchange‘);
    })
    let btn1 = document.getElementById(‘btn1‘)
    let btn2 = document.getElementById(‘btn2‘)
    btn1.addEventListener(‘click‘, (e) => {
    })
</script>

index.html文件

<body>
    <div id=‘root‘>
        测试
    </div>
</body>
<script>
    function callBack(data){
        var box = document.createElement(‘div‘)
        box.innerText = ‘回来了‘
        root.appendChild(box)
    }
    function genScript(url){
        var newS = document.createElement(‘script‘);
        newS.src = url
        window.onload = function(){
            root.appendChild(newS)
        }
    }
</script>
<script>
    var root = document.getElementById(‘root‘)
    genScript(‘http://localhost:8080/test?cb=callback‘)
</script>

app.js文件

const http = require(‘http‘)
const fs = require(‘fs‘)
const httpPort = 8080

http.createServer((req, res) => {
  fs.readFile(‘home.html‘, ‘utf-8‘, (err, content) => {
    console.log(req.url);
    if (err) {
      console.log(‘We cannot open "index.html" file.‘)
    }
    console.log(‘接收到‘);
    res.writeHead(200, {
      ‘Content-Type‘: ‘text/html; charset=utf-8‘
    })

    res.end()
  })
}).listen(httpPort, () => {
  console.log(‘Server listening on: http://localhost:%s‘, httpPort)
})

https://juejin.cn/post/6844903552519766029

单页面应用hash、history原理以及JSONP的分析

上一篇:go学习 06 结构体变量与json字符串互相转换


下一篇:字符串_习题课_4|学习笔记