转载来源:http://blog.csdn.net/alinaxz/article/details/6621563
1、在spring配置文件中加入xmlViewResolver
xml 代码
- <!-- 定义XML view -->
- <bean id="xmlViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
- <property name="order" value="1"/>
- <property name="location" value="/WEB-INF/ajax-views.xml"/>
- </bean>
xml 代码
- <bean name="jsonView" class="com.xx.util.AjaxJsonView">
- <property name="contentType">
- <value>text/xml;charset=utf-8</value>
- </property>
- </bean>
java 代码
- response.setContentType("text/xml; charset=UTF-8");
- // Set standard HTTP/1.1 no-cache headers.
- response.setHeader("Cache-Control",
- "no-store, max-age=0, no-cache, must-revalidate");
- // Set IE extended HTTP/1.1 no-cache headers.
- response.addHeader("Cache-Control", "post-check=0, pre-check=0");
- // Set standard HTTP/1.0 no-cache header.
- response.setHeader("Pragma", "no-cache");
- JSONArray jsonArray = (JSONArray)map.get("ajax_json");
- response.getWriter().write(jsonArray.toString());
java 代码
- public ModelAndView isEmptyOfCategory(HttpServletRequest request,
- HttpServletResponse response) throws Exception{
- //ajax method?
- boolean isAjax = RequestUtils.getRequiredBooleanParameter(request, "ajax");
- //others parameters
- jsonObject.putOpt("categoryId", category_id);
- jsonObject.putOpt("categoryName", category.getName());
- isEmpty = false;
- jsonObject.putOpt("isEmpty", isEmpty);
- String view = null;
- if (isAjax) view = this.getJsonView();
- return new ModelAndView(view, "ajax_json", jsonObject);
- }
js 代码
- $.get('controller?method=isEmptyOfCategory',{id: id, ajax: 'true'},function(response) {
- try {
- var json = eval(response);
- for (var i = 0; i < json.length; i++) {
- alert(json[i].isEmpty);
- }
- } catch(e) {
- alert("Error in JSON response:"+e);
- }
- });