提问者:小点点

vanilla js中的Ajax get请求


我试图将数据从服务器发送到一个网页,但当我将数据登录到控制台时,“null”被打印出来。

我的ejs文件代码(home.ejs):

    <div class="body">
      <button id="get" onclick="getData()">Get data</button>
    </div>
   <script>
    function getData(){
        const xhr=new XMLHttpRequest();
        xhr.open('GET','/num');
        xhr.responseType='json';
        xhr.onload=()=>{
            const data=xhr.response;
            console.log(data);
        }
        xhr.send();
    }
   </script>

我的NodeJs服务器代码:

    app.get('/',(req,res)=>{
     res.render('home');
    })
    app.get('/num',(req,res)=>{
     res.send('success');
    })

我正在将字符串'success'作为数据发送到网页。 我是AJAX请求的新手,我知道这个问题非常基本。 如果有人纠正我的话会很有帮助的。 我只需要香草JS里的答案。


共1个答案

匿名用户

使用XMLHttpRequest有点麻烦。 我建议您使用fetch函数,如下所示:

fetch('/num')
    .then((response) => response.text())
    .then((text) => console.log(text));

因为您要将一个纯字符串发送回客户端,所以需要使用响应对象的text方法。