function getJson(){
$.ajax({
type:"get",
dataType:"json",
url:"<%=basePath %>getJson",
success:function(data){
for(var i=0;i<jsonData.length;i++){
alert("Id:"+data[i].id+" username:"+data[i].username);
}
},
error:function(e){
alert(e);
}
})
}
@ResponseBody
@RequestMapping("/getJson")
public Object getJson(){
return new Object();
}
注意:
使用手动写的json工具类
@RequestMapping("/getJson")
public void getJson(HttpServletResponse response){
Object obj = new Object();
JSONObject json = JSONObject.fromObject(obj);
JsonUtils.ajaxJson(json.toString(), response);
}
附上JsonUtils工具类的代码:
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
public class JsonUtils {
public static void ajaxJson(String jsonString,HttpServletResponse response) {
ajax(jsonString, "application/json",response);
}
public static void ajax(String content, String type,HttpServletResponse response) {
try {
response.setContentType(type + ";charset=UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().write(content);
response.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}