我遇到一个问题,当有人添加标签时,我只需要更新网页的一部分,而不是整个页面。
哈巴狗前端:
h2 Labels
each labelName in label
h4 #{(JSON.stringify(labelName)).substr(1).slice(41, -1).replace(/['"]+/g, '')}
h2 Add a label
form(action='/labeling/#{name}/add_label', method='post', id='insertLabel')
label(for='insertLabel ') Add label
input(type='text', value='', name='label', id='insertLabel')
button(type="submit") submit
单击“提交”会发出一个发布请求,该请求将在此处的中间件中处理
router.post('/labeling/:stream_name/add_label', function (req, res, next) {
overallTime = '00:00:15'
labelName = req.body.label
db_label.insertLabel(labelName, overallTime)
db_label.findLabels((err, labels) => {
if (err) {
return res.sendStatus(500)
}
res.redirect('/labeling/' + outputName)
})
insertLabel将labelName和overallTime插入mongoDB,findLabel返回相关集合中存储的标签,结果如下
[ { _id: 5a7201d8a6a06f1627ad75ba, label: 'moo: 00:00:16' },
{ _id: 5a7201e9a6a06f1627ad75bb, label: 'moo2: 00:00:26' } ]
但是我在收到的所有信息中迷失了方向。在这种情况下,我应该使用 Jquery/Ajax,只是 Ajax、Axios 还是普通 Javascript?
最佳答案
jQuery 会很有用。
这需要位于页面头部或页面末尾之前。
注意:我已重命名您的表单。您必须拥有唯一的 ID!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script>
$(function() {
$("#insertLabelForm").on("submit",function(e) {
e.preventDefault(); // stop submission
// sending all form data - you can also do { "label": $("#insertLabel").val();
// instead of $(this).serialize()
$.post(this.action,$(this).serialize(),function(data) {
$.each(data,function(label) { // loop over result
$("#someContainer").append(label._id+":"+label.label+"<br/>");
});
});
});
});
</script>
关于javascript - 更新页面的一部分而不重新加载整个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48548500/