我正在使用Nodejs res.end()以JSON格式发送数据,并且还将标头设置为application / json,但是我没有在jquery ajax调用的成功函数中获取数据,而是得到了数据直接以JSON格式显示,但我希望它包含在jquery ajax调用的成功函数中,因为我必须在数据表中显示它们。我什至尝试使用res.render()和res.send(),但无法获取它。请帮忙!!
Nodejs代码
router.get('/user_list',(req,res,next)=>{
let new_password = generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
strict: true,
exclude: ["(",")","[","]",":","-",",","{","}","<",">",".","^","/"]
});
connection.query("update user, client set user.status = client.status where user.client_id = client.id",(error,result)=>{
if(error){
console.log(error);
}else{
connection.query('select user.username,user.email,user.msg_id,user.status,system.name from user inner join system on user.system_id = system.id; select id, name from client;',(error,result)=>{
if(error){
console.log(error);
}else{
let value = {values: result,new_password};
//res.json(value);
// res.render('user_list', {user_data: value});
res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(value));
}
})
}
})
})
jQuery代码
$(document).ready(function(){
$.ajax({
url:'user_list',
type:'GET',
//dataSrc: 'user_list',
datatype:'json',
success: function(data){
console.log(data);
$('#example').dataTable({
data:data,
columns: [
{data:'values[0][1].username'},
{data:'values[0][1].name'},
{data:'values[0][1].email'},
{data:'values[0][1].msg_id'},
]
});
}
});
});
答案 0 :(得分:1)
请尝试此操作,以便我们缩小问题范围:
router.get('/user_list', function (req, res) {
const list = [
{ id: 0, name: "Alice"},
{ id: 1, name: "Bob"}
];
res.send(list);
});
在您的索引/脚本中:
$(document).ready(function () {
$.getJSON('user_list').then(res => {
console.log(res);
});
});
这应该在控制台中显示阵列。