ajax从服务器获得响应

时间:2015-11-30 12:22:16

标签: javascript jquery ajax

我无法从我的服务器获得响应(这应该给我一些数字的平均值。

服务器代码:

var path = require('path');
const FileDirectory = "./";
var sum = 0;
var count = 0;

http.createServer(function(req, res) {
    console.log('request starting:'+req.method+" "+req.url);
    var dirName = path.dirname(req.url).toLowerCase();
    var baseName = path.basename(req.url).toLowerCase();
    var extName = path.extname(req.url).toLowerCase();


    // handling "GET /grade" requests
    if (req.method.toLowerCase() === 'get' && req.url.toLowerCase()==='/grade') {
        if (count>0) {
            currentAverage = sum/count;
        }
        else {
            currentAverage = "NaN";
        }
    }

    // handling "POST /grade/1..5" requests
    if (req.method.toLowerCase() === 'post' && dirName === '/grade') {

        sum = sum + parseInt(baseName);
        count++;
        currentAverage = sum/count;
        console.log("Sum:"+sum + " Count:" + count + " Average:" + currentAverage);
    }

    if (!!currentAverage) {
        res.writeHead(200, { 'Content-Type': 'text/html' } );
        res.end(""+currentAverage,'utf-8');
        return;
    }

    res.writeHead(404);
    res.end();
}).listen(8888);

现在,我的客户端代码:

(...)
var xhttp;
              xhttp=new XMLHttpRequest();
              xhttp.onreadystatechange = function() {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                  cfunc(xhttp);
                }
              };
              xhttp.open("POST", 'http://localhost:8888/grade/'+someGrade;
              xhttp.send();
              console.log(xhttp);
              }

$(' .resultAverage&#39)。文本(xhttp.responseText);

任何人都可以告诉我这里有什么问题吗?

1 个答案:

答案 0 :(得分:0)

 $('.resultAverage').text(xhttp.responseText);

应该放在if循环中。在加载dom之前,此语句正在执行。这就是问题