Web前端之路让前端飞

Ajax入门

2017-08-19  本文已影响73人  baiying

Ajax(Asynchronous Javascript +XML)这一项技术能够向服务器请求额外的数据而无需卸载页面.
Ajax的核心是XMLHttpRequest,简称XHR,XHR为向服务器发送请求和解析服务器响应提供了流畅的接口,能够以异步的方式从服务器获得更多信息.

XHR对象

写个小demo练习练习吧

//index.html
<script src="compare.js" type="text/javascript"></script>
<body>
<button id="btn1">获取数据</button>
<div id="progess"></div>
<div id="eles">
</div>
</body>
//compare.js
window.onload = function () {
    var btn = document.getElementById('btn1');
    btn.onclick = getData;
};

function getData() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            document.getElementById('eles').innerHTML = xhr.responseText;
        }
    };
    xhr.open('get', 'http://localhost:3000/', true);
    xhr.send(null);
}
//server.js
var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
    if (req.url == '/' && req.method == 'GET') {
        res.writeHead(200, {
            "Content-Type": "text/plain",
            "Access-Control-Allow-Origin": "http://localhost:63342"
        });
        fs.readFile('info.txt', function (err, data) {
            res.write(data);
            res.end();
        });
    }
}).listen(3000);
//info.txt
hello ,i am baiying . It is a nice day.

打开html文件

Paste_Image.png

点击按钮

Paste_Image.png

一个简单的ajax请求文件内容显示到页面上的demo就完成啦

上一篇 下一篇

猜你喜欢

热点阅读