Ajax get和NodeJS?

时间:2015-09-18 22:17:10

标签: javascript jquery ajax node.js

单击按钮时,我试图在我的网页上显示我的文本文件内容。我使用AJAX来做这件事,我无法弄清楚我的代码有什么问题。

main.js

var http = require('http'),
    fs = require('fs'),
    process = require('child_process');

function send404(res) {
    res.writeHead(404);
    res.write('Error');
    res.end()
}

var value;
var server = http.createServer(function (req, res) {

    if (req.method == 'GET' && req.url == '/') {

        var path = 'java/hello.java'; 

        res.writeHead(200, {'content-type':'text/html'});

        fs.readFile('ajax.html', 'utf8', function (err, data) {

            if (err) {
                return console.log(err);
            } else {
                res.writeHeader(200, {"Content-Type": "text/html"});
                res.write(data);
            }
        });
    }

}).listen(3000);

以下是我的HTML文件代码 ajax.html

<!DOCTYPE html>
<html>
<head>
<script>
    function loadXMLDoc() {
        var xmlhttp;
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "aa.txt", true);
        xmlhttp.send();
    }
</script>
</head>
<body>
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

我的回答基于我认为您正在尝试做的事情:在浏览器中使用AJAX从文件加载一些文本并将其显示在div中。

我的第一个观察是:你不需要任何东西来运行服务器端来实现这一点。 Nodejs的目的是使用Javascript创建服务器端应用程序。因此:您不需要Nodejs。

我的第二个观察是你用JQuery标记了你的问题......但你还没有使用它。 JQuery的一个特性是它包含所有XMLHttpRequest内容,并使其在所有(或几乎所有)浏览器中使用和兼容。因此:你应该使用JQuery。

以下是使用此功能执行您想要执行的操作的一个非常简单的示例:

<div id="myDiv">Hello</div>
<button type="button" id="myButton">Change Content</button>
$(document).ready(function() {
  $("#myButton").on("click", function() {
    $("#myDiv").load("aa.txt");
  });
});

此示例使用JQuery,因此您需要链接到HTML页面中的JQuery库。

答案 1 :(得分:0)

您的HTML代码未按预期运行的原因是因为您尝试从服务器获取文件而未将其设置为提供服务。

尝试查找GET /aa.txt请求并提供文本文件。它应该开始工作:

var http = require('http'),
    fs = require('fs'),
    process = require('child_process');

function send404(res) {
    res.writeHead(404);
    res.write('Error');
    res.end()
}

var value;
var server = http.createServer(function (req, res) {

    if (req.method == 'GET' && req.url == '/') {

        res.writeHead(200, {'content-type':'text/html'});

        fs.readFile('ajax.html', 'utf8', function (err, data) {

            if (err) {
                return console.log(err);
            } else {
                res.writeHeader(200, {"Content-Type": "text/html"});
                res.write(data);
                res.end(); // Else it doesn't seem to end
            }
        });

    } else if (req.method == 'GET' && req.url == '/aa.txt') {

        res.writeHead(200, {'content-type':'text/plain'});

        fs.readFile('aa.txt', 'utf8', function (err, data) {

            if (err) {
                return console.log(err);
            } else {
                res.writeHeader(200, {"Content-Type": "text/plain"});
                res.write(data);
                res.end();
            }
        });

    }

}).listen(3000);

请注意,我添加了此res.end();,因为响应只是在没有它的情况下挂起。

现在,这对我的HTML有效。