【发布时间】:2016-11-07 09:04:11
【问题描述】:
我正在使用 jquery ajax 将表单发布到我的 node.js 服务器。我正在尝试使用 preventDefault 函数防止页面刷新(因为尝试开发 SPA),但令人惊讶的是它正在重定向。而且,数据正在非常顺利地传递到节点快递服务器。但不知何故,它似乎跳过了几行。 当我在基本 POC 中尝试此操作时,一切正常,并且阻止了页面刷新。
$(document).ready(function(){
$('#submit').click(function(event){
//$("form#foodForm").submit(function(event) {
window.alert( event.isDefaultPrevented() );
event.preventDefault();
window.alert( event.isDefaultPrevented() );
console.log("form submitted");
// Prevents the page from refreshing
var $this = $(this); // `this` refers to the current form element
$.post(
'/submittedData', // Gets the URL to sent the post to
$this.serialize(), // Serializes form data in standard format
function(data) {
console.log(data); /** code to handle response **/ },
"json" // The format the response should be in
);
});
});
app.js 代码:
app.post('/submittedData',function(req,res){
console.log('body: ' + JSON.stringify(req.body));
});
HTML 片段:
<form id="foodForm" action="/submittedData" method="post">
<ul> Main course
<li> <input type="checkbox" name="items[]" value="roti">Roti </li>
<li><input type="checkbox" name="items[]" value="biryani">Biryani</li>
<li><input type="checkbox" name="items[]" value="rice">Rice</li>
</ul>
<ul> On the side
<li><input type="checkbox" name="items[]" value="chicken">Chicken</li>
<li><input type="checkbox" name="items[]" value="mutton">Mutton</li>
</ul>
<button id="submit">Submit</button>
<!-- <input type="submit" value="submit" id="submit" > -->
</form>
【问题讨论】:
-
是否也可以显示html代码?当您调用 click 事件时,提交 id 可能尚未在 dom 中。如果是这种情况,可能在文档上使用 .on() 并将点击事件绑定到提交 ID。
-
您好,还添加了 HTML 片段!! :)
-
谢谢。 $("#foodForm").submit(function(evt){evt.preventDefault();}); 怎么样
-
我还看到 html 按钮缺少属性 type="button"。您可以保持 jQuery 代码原样,只需将前面提到的属性添加到您的按钮元素。希望对您有所帮助。
-
嗨,我关注了你的第二条评论,只是添加了 type="button" 属性,奇怪的是,当我点击提交时,什么都没有发生,既没有发布,也没有重新加载..就像死了一样。。
标签: javascript jquery ajax node.js single-page-application