ajax与nodejs实现小交互(html,txt)

ajax.js
//此组件仅实现了html文档的读取,并未实现xml的读取
var btn = document.querySelector("#clickMe");
var http_request = null;

/**客户端的请求程序**/
function makeRequest(url) {
    //创建客户端xml对象
    if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            //解决火狐兼容性
            http_request.overrideMimeType("text/xml");
        }
    } else if (window.ActiveXObject) { //ie不同版本的创建对象
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {}
        }
    }
    //若创建XML对象不成功,则提示。
    if (!http_request) {
        console.log("创建客户端xml对象不成功!终止。")
        //终止函数
        return false;
    } 
    http_request.onreadystatechange = alertContent;
    http_request.open('GET', url, true);
    http_request.send(null);
}

/**处理服务器的响应**/
function alertContent() {
    if (http_request.readyState == 4) { //若收到响应
        if (http_request.status == 200) {
            // 弹出ajax获取到的数据
            alert(http_request.responseText);
        } else {
            console.log("收到响应,但状态码不是200,而是" + http_request.status);
        }
    } else {
        console.log("未收到响应,readyState不为4,为:" + http_request.readyState);
    }   
}

/**按钮的监听事件**/
btn.addEventListener("click",function(){
    makeRequest("/html/content.txt");
}, false);
server.js
var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
var cache = {};

// 请求不到资源,则发送404错误
function send404(response) {
    response.writeHead(404, {"Content-type": "text/plain"});
    response.write("Error 404: Oh my god! The resource not found.");
    response.end();
}
//若不是404,则发送文件
function sendFile(response, filePath, fileContents) {
    response.writeHead(
        200,
        {"Content-type": mime.lookup(path.basename(filePath))}
    );
    response.end(fileContents);
}

//静态文件服务,内部包含发送文件和404
function serveStatic(response, cache, absPath) {
    //若缓存中存在,则从缓存中读取
    if (cache[absPath]) {
        sendFile(response, absPath, cache[absPath]);
    } else {
        // 检查文件是否存在
        fs.exists(absPath, function(exists){
            if (exists) {   //若存在,则读取
                console.log("成功找到的路径为" + absPath);
                fs.readFile(absPath, function(err, data){
                    if (err) {
                        send404(response);
                    } else {
                        cache[absPath] = data;
                        sendFile(response, absPath, data);
                    }
                });
            } else {
                console.log("断点,力求寻找的路径为" + absPath);
                send404(response);
            }
        });
    }
}

//创建服务器
var server = http.createServer(function(request, response){
    console.log("server start.")
    var filePath;
    //设定网站前台的根目录
    if (request.url == "/") {
        filePath = "/html/index.html";
    } else {
        filePath = request.url;  //js img html css
    }
    var absPath = "./" + filePath;
    serveStatic(response, cache, absPath);
}).listen(3000);
文件目录:

sqf

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值