首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

FORM表单AJAX提交方法

Sonder
2020-05-07
2651字
7分钟
浏览 (2.5k)

html:

复制代码
<form action="/addemailcontact" method="POST" id="subform" onsubmit="return false" style="display: block;">
 <div class="form-zone-box">
   <div class="box-left">
     <div class="name"></div>
     <div class="name-box">
       <input type="name" class="form-control text" id="name" placeholder="Full Name" name="Name"></div>
     <div class="name"></div>
     <div class="name-box">
       <input type="email" class="form-control text" id="email" placeholder="Email" name="Email" pattern="^[^\s@]+@[^\s@]+\.[^\s@]+$"></div>
     <div class="name"></div>
     <div class="name-box">
       <input type="subject" class="form-control text" id="subject" placeholder="Subject" name="Subject"></div>
   </div>
   <div class="box-right">
     <div class="name"></div>
     <div class="name-box">
       <textarea type="text" rows="6" class="form-control text textarea" id="content1" placeholder="Message" name="Content"></textarea>
     </div>
     <div>
       <p class="note none" style="color: red;">Can not be empty</p></div>
     <div class="submit-box">
       <button class="submit" type="submit" onclick="sub()">SUBMIT</button></div>
   </div>
 </div>
</form>

js 点击了提交事件:

复制代码
$.fn.serializeObject = function() {
   var o = {};
   var a = this.serializeArray();
   $.each(a,
   function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};
function sub() {
   var myreg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
   var email = $("input[type='email']").val();
   var textarea = $("content1").val();
   if (email !== "" && textarea !== "") {
       if (myreg.test(email)) {
           $.ajax({
               type: "POST",
               dataType: "text",
               contentType: "application/json;charset=UTF-8",
               url: "/addemailcontact",
               data: JSON.stringify($('#subform').serializeObject()),
               success: function() {

},
               error: function() {

}
           });
       }
   } else if (email !== "" || textarea !== "") {

}
}

获取到的结果:

复制代码
{"Name":"11","Email":"814029073@qq.com","Subject":"111","Content":"1111"}
下一篇 / 获取和设置Cookie

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)