在我的服务器文件中,我试图从一个 txt 文件发送数据并像这样在 ajax 中接收它
app.get('/send', function(req, res) {
showData = fs.readFile('file.txt', 'utf8', function(err, data) {
res.send({data:data})
})
})
它到达我的 ajax 代码,我想将它附加到我的 html,但我不能
console.log(response.data)
response.data.forEach(function(val) {
console.log(val.id)
tbodyEl.append('\
<tr>\
<th class="id">' + val.id + '</th>\
</tr>\
')
})
当我从我的服务器文件中发送一个普通的 json 变量时它可以工作但是当我尝试使用文本文件时它没有(说 TypeError: response.data.forEach 不是一个函数)
最佳答案
您包含的代码中有错字 => response.dataata
。
您还需要 JSON.parse()
响应数据。
假设您正在运行的代码没有拼写错误并且响应已被解析,您可能面临的另一个问题是文件包含无效的 JSON 或不包含数组。
关于javascript - 无法将数据从 Node 服务器发送到ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43836422/