实现前后 ajax 的json交互,首先我们导入对应的jar包
Action类
public String getJson() throws IOException {
JSONObject jsonObj = new JSONObject();
JSONObject jsonObject = new JSONObject();
jsonObject.put("success",true);
jsonObject.put("msg","操作成功");
//返回的字符串对象
msg = jsonObject.toString();
return "success";
}
xml配置
<action name="getJson" class="HelloAction" method="getJson">
<!-- 类型必须是 json,package 需要继承 json-default-->
<result name="success" type="json">
<!-- 参数名称必须是 root 文本节点是Action方法的返回字符串-->
<param name="root">msg</param>
</result>
</action>
jsp代码
$.ajax({
url:"getJson.action",
dataType:'json',
type:"post",
success:function(result){
console.log(typeof result);
//转json对象
var rep = eval('('+result+')');
console.log(rep);
//jQuery 提供的转json对象
var obj=$.parseJSON(result);
console.log(obj);
}
});