使用Ajax方法實現分類註冊,並且通過attr()改變input標籤name的屬性
阿新 • • 發佈:2018-12-10
form表單中姓名的id必須要設定,下面會需要用attr()改變name的值,以便傳到後臺對應不同的name欄位
<form method="post"id="myform" name="myform"> 姓名: <input type="text" name="name" id="name" ><br> 密碼: <input type="password" name="password" ><br> 電話號碼:<input type="number" name="phone"><br> 性別:<input type="radio" value="男" name="gender"> 男 <input type="radio" name="gender" value="女"> 女<br> 註冊型別:<select id="object" name="object"> <option value="0">----請選擇身份----</option> <option value="admin">管理員</option> <option value="teacher">教師</option> <option value="parent">家長</option> <option value="student">學生</option> </select> <br/> </form> <input type="button" onclick="register();" value="註冊">
通過attr()改變input標籤的name的屬性,ajax的url通過獲取object設定跳轉到不同的控制層
<script> function register() { var object = $('#object').val(); if (object == "admin"){ $('#name').attr('name','adminname'); }else if(object == "teacher"){ $('#name').attr('name','teachername'); }else if(object == "parent"){ $('#name').attr('name','parentname'); }else if(object == "student"){ $('#name').attr('name','studentname'); } var jsonInfo = $('#myform').serializeObject(); var jsonString = JSON.stringify(jsonInfo); console.log(jsonString); $.ajax({ type:'POST', data:jsonString, url:"/"+object+"/register?t="+new Date().getTime(), contentType:"application/json", success:function (data,type) { alert(data.msg); location.href="/" }, error:function (data) { alert(data.msg); } }) } $.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; }; </script>