jquery ajax发送json格式数据-序列化表单例子 作者:马育民 • 2021-09-22 21:59 • 阅读:10351 需要掌握:[jquery扩展方法-将表单数据转为json对象](https://www.malaoshi.top/show_1IX1uTzNvnOL.html "jquery扩展方法-将表单数据转为json对象") # ajax代码 **注意:** 是发送 `json` 格式的 **字符串**,而不是发送 `json对象` ``` $("#reg").click(function() { // 将表单数据转为 json 对象 var jsonObj = $("#myform").serializeObject(); console.log( jsonObj ) //将json对象转为json字符串 var jsonStr=JSON.stringify( jsonObj ) console.log( jsonStr ) $.ajax({ type: "POST", url: "student", contentType: "application/json; charset=utf-8", data: jsonStr,//发送json字符串 dataType: "json", success: function (data) { alert(1) }, error: function (xhr) { alert('发生错误'); console.log(xhr.responseJSON) // json格式,ajax请求使用该对象 } }); }); ``` **解释:** `$("#myform").serializeObject()` 在 [jquery扩展方法-将表单数据转为json对象](https://www.malaoshi.top/show_1IX1uTzNvnOL.html "jquery扩展方法-将表单数据转为json对象") # 例子 ### html代码 ``` <form id="myform"> 登录名:<input type="text" name="username" value="李雷"><br> 密码:<input type="text" name="password" value="123456"><br> 性别:<input type="radio" name="sex" value="0" >女 <input type="radio" name="sex" value="1" checked>男 <br> 爱好:<input type="checkbox" value="wzry" name="like">王者荣耀 <input type="checkbox" value="cj" name="like" checked>吃鸡 <input type="checkbox" value="douyin" name="like" checked>抖音 <br> 民族: <select name="minzu"> <option value="-1" >--请选择--</option> <option value="1" >汉族</option> <option value="2" selected>满族</option> <option value="3" >蒙古族</option> </select> <br> 描述:<input type="text" name="descrip" value=""><br> <input type="button" value="注册" id="reg"> </form> ``` **提示:**描述应该是 文本域 `textarea`,但在本文本编辑器中,会导致bug所以改成 `input` 标签 ### 引入jquery ``` <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script> ``` ### js代码: ``` <script> $.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; }; $("#reg").click(function() { // 将表单数据转为 json 对象 var jsonObj = $("#myform").serializeObject(); console.log( jsonObj ) var jsonStr=JSON.stringify( jsonObj )//将json对象转为json字符串 console.log( jsonStr ) $.ajax({ type: "POST", url: "student", contentType: "application/json; charset=utf-8", data: jsonStr, dataType: "json", success: function (data) { alert(1) }, error: function (data) { alert(JSON.stringify(data)); } }); }); </script> ``` 原文出处:/show_1IX1uU8KHdzS.html