javascript
java ajaxsubmit_ajaxSubmit返回JSON格式
開(kāi)發(fā)時(shí)遇到根據(jù)不同情況返回錯(cuò)誤提示信息的需求,用到了ajax中返回json格式數(shù)據(jù)的。
前臺(tái)請(qǐng)求代碼:
function login() {
$.ajax({
//幾個(gè)參數(shù)需要注意一下
type: "POST",//方法類(lèi)型
dataType: "json",//預(yù)期服務(wù)器返回的數(shù)據(jù)類(lèi)型
url: "login.action" ,//url
data: $('#form1').serialize(),
success: function (data) {
console.log(data);//打印服務(wù)端返回的數(shù)據(jù)(調(diào)試用)
if (ata.code ==200) {
alert("登錄成功!");
}else{
alert("登陸失敗!"+data.Msg);
}
;
}
});
}
后臺(tái)接收代碼:
//驗(yàn)證登錄
@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", "驗(yàn)證成功!");
}else {
json.put("code", 400);
json.put("Msg", "密碼錯(cuò)誤");
}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");//防止亂碼
response.getWriter().print(json.toJSONString());
}
后臺(tái)controller中的方法使用時(shí)是返回的JSONObject類(lèi)型,未使用注解,修改為
方法名:?public JSONObjectlogin(User user,HttpServletResponse response)?????? 返回值:return json
注:用到JSONObject()方法需引入6個(gè)jar包,不然會(huì)報(bào)java.lang.NoClassDefFoundError錯(cuò)誤。
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
————————————————
版權(quán)聲明:本文為CSDN博主「程序員xiaoQ」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_42304232/java/article/details/89713452
總結(jié)
以上是生活随笔為你收集整理的java ajaxsubmit_ajaxSubmit返回JSON格式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: hadoop-2.7.2 分布式集群搭建
- 下一篇: java 无法加载资源,JavaScri