关于spring 通过ajax返回json的问题?
请问spring 通过ajax怎么返回json呢?
这里是我的代码:
前台:
function xiao(){
$.ajax({
url: "<%=basePath %>/ajax/getStars.do",
contentType: "application/json;charset=utf-8",
type: "get",
dataType: "json",
success: function(data) {
alert(data);
},
error: function() {
alert("系统发生异常,请稍候再试!\n\n有任何疑问,请联系系统管理员!");
}
});
}
@Controller
public class Ajax {
@Autowired
private StarService starService;
private static final Logger logger = LoggerFactory.getLogger( Ajax.class );
@RequestMapping( value = "/ajax/getStars", method = RequestMethod.GET )
@ResponseBody
public String getAllStar( HttpServletResponse response ) {
logger.info( "异步查询明星" );
List<Star> stars = starService.getAllStar();
return null;
}
}
import net.sf.json.JSONObject;
dataType: "json",
@Controllerjs取值的时候, data就是你要取的list。
public class Ajax {
@Autowired
private StarService starService;
private static final Logger logger = LoggerFactory.getLogger( Ajax.class );
@RequestMapping( value = "/ajax/getStars", method = RequestMethod.GET )
@ResponseBody
public List getAllStar( HttpServletResponse response ) {
logger.info( "异步查询明星" );
List<Star> stars = starService.getAllStar();
return stars;
}
}
$.getJSON(“url”, 回调函数);jquery这个可以直接获取json数据,方便
$.getJSON(“url”, 回调函数);
JSONObject json = new JSONObject();
json.put("endWarehouseList", routeSearchBeanList);
super.response().setCharacterEncoding("UTF-8");
try {
PrintWriter printWrite = super.response().getWriter();
printWrite.write(json.toString());
printWrite.flush();
printWrite.close();
} catch (IOException e) {
logger.error(e, e);
}finally{
super.response().getWriter().close();
}
@Controller
public class AjaxAction {
@Autowired
private StarService starService;
// private static final Logger logger = LoggerFactory.getLogger( AjaxAction.class );
@RequestMapping( value = "/ajax/getStars" )
@ResponseBody
public Object getAllStar( HttpServletResponse response, HttpServletRequest request ) {
// logger.info( "异步查询明星" );
List<Star> stars = starService.getAllStar();
JSONArray json = JSONArray.fromObject( stars );
return json.toString();
}
}
JSONArray json = JSONArray.fromObject( stars );