javascript
java ajaxsubmit_ajaxSubmit返回JSON格式
開發時遇到根據不同情況返回錯誤提示信息的需求,用到了ajax中返回json格式數據的。
前臺請求代碼:
function login() {
$.ajax({
//幾個參數需要注意一下
type: "POST",//方法類型
dataType: "json",//預期服務器返回的數據類型
url: "login.action" ,//url
data: $('#form1').serialize(),
success: function (data) {
console.log(data);//打印服務端返回的數據(調試用)
if (ata.code ==200) {
alert("登錄成功!");
}else{
alert("登陸失敗!"+data.Msg);
}
;
}
});
}
后臺接收代碼:
//驗證登錄
@RequestMapping(value="/login",method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
@ResponseBody
public void login(User user,HttpServletResponse response) throws IOException{
JSONObject json=new JSONObject();
if (user.getUpassword().equals("123")) {
json.put("code", 200);
json.put("Msg", "驗證成功!");
}else {
json.put("code", 400);
json.put("Msg", "密碼錯誤");
}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");//防止亂碼
response.getWriter().print(json.toJSONString());
}
后臺controller中的方法使用時是返回的JSONObject類型,未使用注解,修改為
方法名:?public JSONObjectlogin(User user,HttpServletResponse response)?????? 返回值:return json
注:用到JSONObject()方法需引入6個jar包,不然會報java.lang.NoClassDefFoundError錯誤。
json-lib-2.4-jdk15.jar
commons-beanutils-1.8.0.jar
commons-logging-1.1.1.jar
commons-collections-3.2.1.jar
commons-lang-2.5.jar
ezmorph-1.0.6.jar
————————————————
版權聲明:本文為CSDN博主「程序員xiaoQ」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_42304232/java/article/details/89713452
總結
以上是生活随笔為你收集整理的java ajaxsubmit_ajaxSubmit返回JSON格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hadoop-2.7.2 分布式集群搭建
- 下一篇: java 无法加载资源,JavaScri