我试图将数据从服务器发送到一个网页,但当我将数据登录到控制台时,“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里的答案。
使用XMLHttpRequest
有点麻烦。 我建议您使用fetch
函数,如下所示:
fetch('/num')
.then((response) => response.text())
.then((text) => console.log(text));
因为您要将一个纯字符串发送回客户端,所以需要使用响应对象的text
方法。