Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ajax从服务器获取响应_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript ajax从服务器获取响应

Javascript ajax从服务器获取响应,javascript,jquery,ajax,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.dir

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

服务器代码:

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').text(xhttp.responseText)

有人能告诉我这里怎么了吗

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

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

您是否使用服务器端语言(如PHP)?
$('.resultAverage').text(xhtp.responseText);
应该放在
if(xhtp.readyState==4和&xhttp.status==200)之后{
很抱歉,这不是问题所在,这是我糟糕的编辑-我收到了关于缺少CORS头的回复,我不知道那是什么。。