【发布时间】:2023-03-29 04:50:01
【问题描述】:
[REGISTER SHIFT/ ASSIGNMENT FORM]
这是我的表格,让我描述一下;它注册下周工作时间,我设计有2个案例:添加新和编辑在同一个表格中。
当用户选择一个员工时,如果还没有注册班次,我们让用户注册这个员工,如果班次已经注册,用户可以在同一个表单中编辑。而且我认为最好不要刷新页面,每次用户更改员工时,表单只是更新并让用户添加/编辑然后通过post方法提交。
我在网上搜索,找到了一个 ajax/jQuery 的推荐。
还有什么推荐给我的吗?我刚刚学习了使用 PostgreSQL 数据库的 Nodejs/Express。
我正在尝试使用 ajax 从 post 事件加载我的页面,我在 ajax 中调用错误函数来查看错误是什么并得到:
解析 JSON 请求失败。状态 200。
我正在使用 NodeJS Express 服务器、EJS 视图引擎、body-parser、postgresql db。
pool.connect((err, client, release) => {
if (err) {
return console.error('Error acquiring client', err.stack)
}
client.query(
'SELECT * FROM "Employee"', (err, result) => {
release()
if (err) {
res.end();
return console.error('Error executing query', err.stack);
}
console.log(typeof(result));
res.type('json');
res.render("index", {emplist : result});
res.end();
})
})
我的ajax函数:
$.ajax({
url: "/addshift",
type: "POST",
data: JSON.stringify(employee),
dataType: "application/json",
contentType: 'application/json',
complete: function () {
console.log("go into complete !");
},
success: function (response) {
console.log(response);
console.log("go into success !");
},
error:function(x,e) {
if (x.status==0) {
alert('You are offline!!\n Please Check Your Network.');
} else if(x.status==404) {
alert('Requested URL not found.');
} else if(x.status==500) {
alert('Internel Server Error.');
} else if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed. ' + x.status);
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
【问题讨论】:
-
res.render("index", {emplist : result});是否返回 json?我相信这会返回一些 html,但您的 ajax 调用需要一个 json 而不是 html -
@Gonzalo.- 索引是一个 ejs 文件,结果是一个对象,我从 pg db 查询它
-
@Gonzalo.- 我的 ajax 函数看起来像 $.ajax({ url: "/addshift", type: "POST", data: JSON.stringify(employee), dataType: "application/json ", contentType: 'application/json', ...
-
ejs 是渲染html。即使 result 变量是一个对象, res.render 也会获取该对象并构建 html 并将其发送回您的前端。你的前端期望 json 吗?还是包含对象定义的html?看出区别了吗?
-
而不是
res.render()尝试使用res.json(result);
标签: node.js json ajax postgresql express