用jQueryAjax序列化表單後臺取不到資料問題
阿新 • • 發佈:2019-01-02
Ajax後臺取不到資料問題
前端程式碼
<form onsubmit="return modifyEmployees()" id="modifyEmployees" > <table class="layui-table"> <tr style="border: 0px"> <td>員工編碼</td> <td> <input name="e_Code" class="layui-input" type="text" th:value="${newEmployee.e_Code}"/> </td> </tr> <tr> <td>員工姓名</td> <td> <input name="e_RealName" class="layui-input" type="text" th:value="${newEmployee.e_RealName}"/> </td> </tr> <tr> <td>性別</td> <td> <input type="radio" name="e_Sex.sex_Id" value="1" id="male" th:checked="${newEmployee.e_Sex.sex_Id eq 1}"/> <label for="male">男</label> <input type="radio" name="e_Sex.sex_Id" value="2" id="female" th:checked="${newEmployee.e_Sex.sex_Id eq 2}"/> <label for="female">女</label> </td> </tr> <tr> <td>狀態</td> <td> <input type="radio" name="e_Status.st_Id" value="1" id="normal" th:checked="${newEmployee.e_Status.st_Id eq 1}"/> <label for="normal">正常</label> <input type="radio" name="e_Status.st_Id" value="2" id="disable" th:checked="${newEmployee.e_Status.st_Id eq 2}"/> <label for="disable">禁用</label> </td> </tr> <tr> <td>所屬部門</td> <td> <select name="e_DeptId.d_Id" class="layui-select" > <option value="0">--請選擇--</option> <option th:selected="${newEmployee.e_DeptId.d_Id eq dept.d_Id}" th:each="dept:${depts}" th:value="${dept.d_Id}" th:text="${dept.d_Name}"></option> </select> </td> </tr> <tr> <td>角色身份</td> <td th:text="${newEmployee.e_Role.r_Name}"></td> </tr> <tr> <td>備註資訊</td> <td> <textarea name="e_Description" class="layui-textarea" th:value="${newEmployee.e_Description}"></textarea> </td> </tr> <input name="e_Id" type="hidden" th:value="${newEmployee.e_Id}"/> <tr> <td colspan="2" style="text-align: center"> <input type="submit" value="提交" class="layui-btn layui-bg-blue"/> <input type="button" value="返回" class="layui-btn layui-bg-blue" onclick="back()"/> </td> </tr> </table> </form>
Ajax程式碼
function modifyEmployees() { var emp = ($("#modifyEmployees").serialize()); $.ajax({ //幾個引數需要注意一下 type: "POST",//提交型別 contentType:'application/json;charset=UTF-8', dataType: "json",//預期伺服器返回的資料型別 url: "/modifyEmployees" ,//url data: emp,//序列化表單資訊 success: function (data) { if (data == true) { layer.msg("修改成功!"); parent.$("#employees").DataTable().ajax.reload(); }else{ layer.msg("修改失敗!"); } } }); return false; }
後臺返回的資訊
就是後臺取不到值,很煩!找了半天原因是因為Ajax,contentType的值:
contentType:‘application/json;charset=UTF-8’,
這個型別的值填錯了應該改為:
contentType:‘application/x-www-form-urlencoded’,
這樣就可以了;