前台页面当点击a标签按钮是触发ajax发送post值到后台
<script>
$('a[type="submit"]').on('click', function() {
let name = $('#name').val();
let age = $('#age').val();
let sex = $('#sex').val();
let phone = $('#phone').val();
let address = $('#address').val();
let introduction = $('#introduction').val();
$.ajax({
type: "post",
url: "/student/add",
data: {
name: name,
age: age,
sex: sex,
phone: phone,
adress: address,
introduction: introduction
},
dataType: "json",
success: function(response) {
console.log(response);
}
});
})
</script>
后台自己封装的添加数据函数
/**
* 新增一条数据
* @param {*集合名称} collectionName
* @param {*新增条件} condition
* @param {*回调函数} callback
*/
let fn_insertOne = (collectionName, condition, callback) => {
getDB((db) => {
//获取集合
db.collection(collectionName).insertOne(condition, (err, result) => {
callback(err, result);
db.close();
})
})
}
添加数据在这里实现
let fn_add = function(req, res) {
Db.insertOne('student', req.body, (err, result) => {
if (result == null) { //失败
res.setHeader("Content-Type", "text/html;charset=utf8")
res.end("<script>alert('新增失败')</script>")
} else { //成功
res.setHeader("Content-Type", "text/html;charset=utf8")
res.end("<script>window.location.href='/studentmanager/list'</script>")
}
})
}
说明:很明显我是需要添加数据成功之后写入一段脚本跳回list页面
问题:点击添加数据按钮数据添加成功之后页面不跳转,打开浏览器调试返回的脚本内容在response里面。
把
window.location='/studentmanager/list
添加到ajax成功后success的回调函数中试试