44-【前后分离】AJAX 的原理


全文源码地址 https://github.com/yf2050/AJAX-1
AJAX技术 是 asyns异步 Javascript And XML

作用:js发请求和收响应

AJAX是浏览器提供的功能,浏览器可以发送请求和收响应,所以浏览器给window上加一个全局函数,XMLHttpRequest构造函数,实现js发请求和收响应

window.XMLHttpRequest
ƒ XMLHttpRequest() { [native code] }
window.Object
ƒ Object() { [native code] }
下载server.js模拟服务器

github里下载
github里快速复制代码内容:从后面选按住shift点击最前面

npm node-dev 自动重启node进程

yarn global add node-dev

node-dev server.js 8888
复习server.js并简化代码

写index.html路由 ,路由就是if else

index.html

response.write(`
<!DOCTYPE>
<html>
<head><title>AJAX</title></head>
<body>
    <h1>AJAX demo1</h1>
</body>
</html>
`)

写main.js路由

else if (path === '/main.js') {
        response.statusCode = 200
        response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
        response.write(`console.log('主要js')`)
        response.end()
    }

合并路由

<!DOCTYPE>
<html>
<head><title>AJAX</title></head>
<body>
    <h1>AJAX demo1</h1>
<script src='main.js'></script>
</body>
</html>

简化response.write(‘字符串’):文件转字符串fs.readFileSync(‘public/index.html’)

const string = fs.readFileSync('public/index.html')
response.write(string)
AJAX实现CSS
getCSS.onclick = () => {
   
    const request = new XMLHttpRequest();//第一步:创造新的对象
    request.open('GET', '/style.css')//第二步:实现对象open()方法,初始化请求
    request.onload = () => {
   //第三步,对象监听事件
        console.log('成功')
        console.log(request.response)
        //创建style标签
        const style = document.createElement('style')
        //style插入内容
        style.innerHTML = request.response
        //把style插入头部
        document.head.appendChild(style)
    }
    request.onerror = () => {
   
        console.log('失败')
    }
    request.send() //第四步:调用对象send方法,发送 HTTP 请求
}

要点:

  • 先启动服务器:node-dev server.js 8888
  • 进入localhost主页面
  • 触发获取css事件
  • request.response是请求的响应,作为标签内容
AJAX加载JS

原始方法:public里创建2.js,之后连接script

AJAx方法:

getJS.onclick = () => {
   
    const request = new XMLHttpRequest()
    request.open('GET', '2.js')
    request.onload 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值