jQuery中form.serialize()返回空字符串问题求助
表单serialize()返回空字符串的解决办法
问题描述
我在表单的submit事件中调用serialize()方法,以获取表单输入内容并阻止表单默认提交行为。已确认所有输入框都设置了name属性且未处于禁用状态,但.serialize()仍返回空字符串,恳请提供帮助!
我的HTML代码(Pug语法)
div(class='waitlist' id='waitlist') h1(id='waitlisttext') Add me to the waitlist form(action="" id='waitlistform') // target="_blank" method="POST" action="../waitlistdata.php"// label(for="fname") First name: br input(type="text", id="fname", name="fname", value="" required) br label(for="lname") Last name: br input(type="text", id="lname", name="lname", value="" required) br label(for="email") Email: br input(type="text" id="email" name="email" value="" required) br br input(type="submit" name="submit" value="Submit")
我的提交函数JS代码
$("#waitlist").on("submit", function(e) { console.log('submit function called') console.log(document.getElementById('fname').disabled) var dataString = $(this).serialize(); alert(dataString); return false; $.ajax({ type: "POST", url: "../views/waitlistdata.php", data: dataString, success: function () { $("#waitlisttext").html("<div id='message'></div>"); $("#message") .html("<h2>Contact Form Submitted!</h2>") .append("<p>We will be in touch soon.</p>") .hide() .fadeIn(1500, function () { $("#message").append( "<img id='checkmark' src='images/check.png' />" ); }); } }); e.preventDefault(); return false; });
问题原因与解决办法
事件绑定对象错误
你把submit事件绑定在了#waitlist这个div元素上,而serialize()方法只能作用于表单元素。div不是表单,调用它的serialize()自然返回空字符串。提前return导致后续代码失效
在alert(dataString);之后直接写了return false;,导致后面的AJAX请求和e.preventDefault();都不会执行,虽然这不是serialize为空的原因,但也是代码逻辑的问题。
修正后的JS代码
$("#waitlistform").on("submit", function(e) { console.log('submit function called') console.log(document.getElementById('fname').disabled) var dataString = $(this).serialize(); alert(dataString); $.ajax({ type: "POST", url: "../views/waitlistdata.php", data: dataString, success: function () { $("#waitlisttext").html("<div id='message'></div>"); $("#message") .html("<h2>Contact Form Submitted!</h2>") .append("<p>We will be in touch soon.</p>") .hide() .fadeIn(1500, function () { $("#message").append( "<img id='checkmark' src='images/check.png' />" ); }); } }); e.preventDefault(); return false; });
说明
- 将事件绑定目标改为表单元素
#waitlistform,此时$(this)指向表单,调用serialize()就能正确收集所有带name属性的输入框值。 - 移除了提前的
return false;,确保AJAX请求和默认行为阻止代码能正常执行。
内容的提问来源于stack exchange,提问作者jendeukstan
相关产品推荐
相关产品推荐

