【问题标题】:i am making the ajax call from the html to nodejs我正在从 html 到 nodejs 进行 ajax 调用
【发布时间】:2015-04-09 12:50:02
【问题描述】:

我正在从 html 到 nodejs 进行 ajax 调用以从服务器检索数据,数据正在从服务器返回但在浏览器中它没有显示

//html code
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>      
        <script>
            function changeText1() {
                var myRequest = new XMLHttpRequest();
                myRequest.onreadystatechange=function() {
                if(myRequest.status==200 && myRequest.readystate==4) {
                    console.log("successfully received ");
                    var name=JSON.parse(myRequest.responseText);
                    console.log(name);
                    document.getElementById("myDiv").innerHTML = name.title;
                } else {
                    console.log("Cannot process");
                }
            }
            myRequest.open("GET","http://localhost:3000/endpoint",true);
            myRequest.send(null);
        }
        </script>
    </head>
    <body>
        <div id="myDiv">Hello welcome</div>
        <button type="button" onclick="changeText1()">Change Content</button>
    </body>
</html>

//服务器端代码(在nodejs中)

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(express.static(__dirname+"/"));


app.get('/endpoint', function(req, res) {
    var obj = {};
    obj.title = 'Ajax project';
    //obj.data = 'Welcome';

    res.header('Content-type','application/json');
    res.header('Charset','utf8');
    console.log(JSON.stringify(obj));
    res.send(JSON.stringify(obj) );
});

app.listen(3000);
console.log("Server started");

正在从服务器检索数据 但是控件无法进入

if(myRequest.status==200 && myRequest.readystate==4)

显示器无法处理

【问题讨论】:

  • 做一个 console.log("Status:" + myRequest.status + "readyState: " +myRequest..readyState) 看看你得到了什么。
  • 除非我忽略了某些事情,否则您从不将您的请求发送到任何地方?

标签: javascript html ajax node.js express


【解决方案1】:

readyState 是用 camelCasing 而不是 'readystate' 编写的,这就是为什么你看不到结果,'readystate' 是未定义的。我强烈建议您在 if 语句中使用 '===' 而不是 '=='。

我也会在你打开请求后编写这段代码。

myRequest.onreadystatechange = function () {
   if(myRequest.readyState === 4) {
      if(myRequest.status === 200) { //DO STUFF}
   }
}

【讨论】:

    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多