1,jQuery的post方法,传递json已经接收json格式。
如:function doService(){
var url="test!doService";
var obj={};
obj.name="xclsky";
var type="json";
jQuery.post(url,{"obj":JSON.stringify(obj)},function(data){
alert(data.returnValue);
},type);
}
jQuery.post参数为url,data,success function(),type。
如果想让json转为string,通过JSON.stringify()。eval是将String转化为json。
success function(data,textstatus,xhr)data为传回来的参数为json格式。
在js中得到json中的值,直接通过".",如data.returnValue。
2,后台:public String doService() throws IOException{
HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();
String obj=request.getParameter("obj");
PrintWriter out=response.getWriter();
response.setContentType("text/json;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
JSONObject json=JSONObject.fromObject(obj);
String value=json.getString("name");
JSONObject json1=new JSONObject();
value=value+"--json";
json1.element("returnValue",value);
//out.append(json1.toString());
out.print(json1);
out.flush();
out.close();
return null;
}
在后台可以通过action中调用,只要返回的null即可。
首先要设置response.setContentType("text/json;charset=UTF-8"),response.setHeader("Cache-Control","no-cache");
通过JSONObject.fromObject()来得到json格式的数据。
可以通通过json.element()来讲值添加到josn中。
最后通过out.print(json)将json传递给前台。
如:function doService(){
var url="test!doService";
var obj={};
obj.name="xclsky";
var type="json";
jQuery.post(url,{"obj":JSON.stringify(obj)},function(data){
alert(data.returnValue);
},type);
}
jQuery.post参数为url,data,success function(),type。
如果想让json转为string,通过JSON.stringify()。eval是将String转化为json。
success function(data,textstatus,xhr)data为传回来的参数为json格式。
在js中得到json中的值,直接通过".",如data.returnValue。
2,后台:public String doService() throws IOException{
HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();
String obj=request.getParameter("obj");
PrintWriter out=response.getWriter();
response.setContentType("text/json;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
JSONObject json=JSONObject.fromObject(obj);
String value=json.getString("name");
JSONObject json1=new JSONObject();
value=value+"--json";
json1.element("returnValue",value);
//out.append(json1.toString());
out.print(json1);
out.flush();
out.close();
return null;
}
在后台可以通过action中调用,只要返回的null即可。
首先要设置response.setContentType("text/json;charset=UTF-8"),response.setHeader("Cache-Control","no-cache");
通过JSONObject.fromObject()来得到json格式的数据。
可以通通过json.element()来讲值添加到josn中。
最后通过out.print(json)将json传递给前台。