我的开发环境:struts2.1.8.1   、struts2-plugin-json-2.1.8.1 <script type="text/javascript">
  $(function(){
          $("#hotel").bind("change",function(){
           var hotel=$("#hotel").val();   
              alert(hotel);
              $.ajax({
               url :'bedajax_getRoom.action',  
               type:'post',
               data:'hotelId='+$("#hotel").val(),
   dataType:'json',
   success:function(json){
     var roomList=json.roomList;
                var html = "";
                   html+="<table><tr><td>房间编号:</td><td>"+roomList.roomCode+"</td></tr></table>";
                 $("#showRoom").html(html);   }
               });
              })    })
</script>
 <package name="ajax" extends="json-default">  
               <action name="bedajax_*" class="bedAction" method="{1}">

          <result type="json"></result>
</action>
    </package>  public  String getRoom() throws Exception{
 HttpServletRequest request=ServletActionContext.getRequest();
 String hotelId=request.getParameter("hotelId");
  Long hotel=Long.parseLong(hotelId);
roomList=bedService.roomsSelected(hotel);
return SUCCESS;
}=========================================================================================ajax可以进到action里,但是回到函数获取不到东西....
success:function(json){
     var roomList=json.roomList;
                var html = "";
                   html+="<table><tr><td>房间编号:</td><td>"+roomList.roomCode+"</td></tr></table>";
                 $("#showRoom").html(html);   }
何解?

解决方案 »

  1.   

    后台是这样子输出json的 
    public  String getRoom() throws Exception{
        HttpServletReponse response = ServletActionContext.getResponse();
        response.getWrite().print(json);
        response.getWrite().close();
        return null;
    }
      

  2.   

    jsp页面 ajax的回到函数为什么没有结果呢?我alert(json);没反应...
      

  3.   


    你后台都没有传递json ,前台怎么获取呢?
      

  4.   

    success: function(data)
    ---------------------------------------------------------------------
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("application/x-javascript;charset=UTF-8");
    response.getWriter().write("{\"result\":\"OK!\"}");
      

  5.   

    success:function(json){
    或者JSON Plugin,它可以将Struts2 Action中的结果直接返回为JSON
      

  6.   

    这个东西~~~我也不是很清楚!!!配置有很多种!方法也好像有很多种!
        如果LZ知道~~~希望结贴的时候给好好总结总结、在分享分享!
    下面是我以前做的一个! http://blog.csdn.net/hzw2312/archive/2011/04/14/6322325.aspx
      

  7.   

    我没有看到楼主有返回json的代码~~
      

  8.   

    1 success:function(json){
         alert(json);//能否打出东西
          ...2 response.getWrite().print(json);
      System.out.println(json);//把json打印出来,看看是否格式正确3 bedajax_getRoom.action 直接在地址栏访问,看看是否有调用返回
      

  9.   

    1 success:function(json){
      alert(json);//能否打出东西   ==================》答:答应不出来
     2.response.getWrite().print(json);      =================》答:好像执行不到这句
    3 bedajax_getRoom.action 直接在地址栏访问,看看是否有调用返回================》已经调用到
      

  10.   

    这位兄弟,非常感谢,看了你的帖子,遇到的情况和困惑基本上一样,于是也模仿了你的代码,但是
           error : function(e) {   
                      alert("error");   ==========》会报error这个错误,下面得
    的success就不会执行了,悲剧了不只2两天...
                          },   
                           success:function(jsonData) {   
                             alert('success');   
      

  11.   

    目前是这么写的.//AJAX根据点酒店获取房间
    public String selectAllRoom() throws Exception{
     HttpServletRequest request=ServletActionContext.getRequest();
     HttpServletResponse response = ServletActionContext.getResponse();  List jsonList = new ArrayList();   
     Logger.getLogger(BedAction.class).info("=============有js发送的请求,将返回room列表====================");
     String hotelId=request.getParameter("hotelId");
     Logger.getLogger(BedAction.class).info("=============接受到的hotelId为:===================="+hotelId);
     if(null!=hotelId&&!"".equals(hotelId)){
     Long hotel=Long.parseLong(hotelId);
     roomList=bedService.roomsSelected(hotel);
     }
     
     for(int i=0;i<roomList.size();i++){
     Room room=roomList.get(i);
               AjaxRoom ar=new AjaxRoom();
               ar.setRoomId(room.getRoomId());
               ar.setRoomCode(room.getRoomCode());
               jsonList.add(ar);
     }
     JSONObject json=JSONObject.fromObject(jsonList);
     result=json.toString();
     response.getWriter().print(result);
    return SUCCESS;
    }
    请老鸟多多指教,在此表示非常感谢....
      

  12.   

    既然都用struts2和json整合的jar包了怎么还在action中还这样写?【response.getWriter().print(result)】我贴一个整合的例子,你可以参考一下:User.javapackage bean;public class User {
    private int id;  
        private String name; 
        private String password;
    public int getId() {
    return id;
    }
    public void setId(int id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public String getPassword() {
    return password;
    }
    public void setPassword(String password) {
    this.password = password;

        
    }
    UserAction.javapackage action;import java.util.ArrayList;
    import java.util.List;import com.opensymphony.xwork2.ActionSupport;import bean.User;public class UserAction extends ActionSupport {
    private String message; // 使用json返回单个值
    private User user; // 使用json返回对象
    private List<User> userList; // 使用josn返回List对象 /* 返回单个值 */
    public String returnMsg() {
    this.message = "成功返回单个值";
    return SUCCESS;
    }
    /* 返回UserInfo对象 */
    public String returnUser() {
    user=new User();
    user.setId(10000);
    user.setName("刘栋");
    user.setPassword("123456");
    return SUCCESS;
    }
    /* 返回List对象 */
    public String returnList() {
    userList=new ArrayList<User>();
    User u1 = new User();
    u1.setId(10000);
    u1.setName("张三");
    u1.setPassword("111111");
    User u2 = new User();
    u2.setId(10001);
    u2.setName("李四");
    u2.setPassword("222222");
    userList.add(u1);
    userList.add(u2);
    return SUCCESS;
    }
    public String getMessage() {
    return message;
    }
    public void setMessage(String message) {
    this.message = message;
    }
    public User getUser() {
    return user;
    }
    public void setUser(User user) {
    this.user = user;
    }
    public List<User> getUserList() {
    return userList;
    }
    public void setUserList(List<User> userList) {
    this.userList = userList;
    }
    }struts.xml<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd"><struts> <constant name="struts.i18n.reload" value="true" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.configuration.xml.reload" value="true" />
    <package name="json" extends="json-default" namespace="/json">
    <action name="returnMsg" class="action.UserAction" method="returnMsg">
    <result name="success" type="json">
    <param name="message">${message}</param>
    </result>
    </action>
    <action name="returnUser" class="action.UserAction" method="returnUser">
    <result name="success" type="json">
    <param name="includeProperties">
    user\.id,user\.name,user\.password
                    </param>
    </result>
    </action>
    <action name="returnList" class="action.UserAction" method="returnList">
    <result name="success" type="json">
    <param name="includeProperties">
    userList\[\d+\]\.id,userList\[\d+\]\.name,userList\[\d+\]\.password
                    </param>
    </result>
    </action>
    </package>
    </struts>index.jsp<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
    + request.getServerName() + ":" + request.getServerPort()
    + path + "/";
    %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <base href="<%=basePath%>">
    <script type="text/javascript" src="<%=path%>/js/jquery-1.4.2.min.js"></script>
    <script language="javascript">
    function getMsg() {
    $.ajax( {
    url : 'json/returnMsg.action',
    type : 'post',
    dataType : 'json',
    success : function(data) {
    $("#result").html(data.message);
    }
    });
    }function getUser() {
    $("#result").html("");
    $.ajax( {
    url : 'json/returnUser.action',
    type : 'post',
    dataType : 'json',
    success :function(data) {
    $("#result").append("用户ID:" + data.user.id + "").append(
    "用户名:" + data.user.name + "").append(
    "密码:" + data.user.password + "");
    }
    });
    }function getUserList() {
    $("#result").html("");
    $.ajax({
             url:'json/returnList.action', 
             type:'post',
             dataType:'json', 
             success:function(data){ 
               $.each(data.userList,function(i,value){   
              $("#result").append("第"+(i+1)+"个用户")
                          .append("编号:"+value.id+"")
                              .append("用户名:"+value.name+"")
                              .append("密码:"+value.password+"")
                              .append("<br/>");
                              ;
               });
             }
          });
        }
    </script>
    </head> <body> <div id="result"></div>
    <input type="button" value="获得单个消息" onclick="getMsg()" />
    <input type="button" value="获得用户信息" onclick="getUser()" />
    <input type="button" value="获得用户列表" onclick="getUserList()" />
    </body>
    </html>
      

  13.   

    用到的jar包:
    struts2-json-plugin-2.1.8.1.jar
    json-lib-2.1.jar
    commons-collections-3.2.jar
    commons-beanutils-1.7.0.jar
    commons-lang-2.3.jar
    commons-logging-1.0.4.jar
    ezmorph-1.0.3.jar
    这7个包是返回json形式的数据必须的。因为json大量引用了Apache commons的包,所以要加入4个,commons包,除了commons的包外,还需要引入一个 ezmorph的包。最后加入struts2必须的6个包:
    struts2-core-2.1.8.1.jar
    xwork-core-2.1.6.jar
    ognl-2.7.3.jar
    freeer-2.3.15.jar
    commons-fileupload-1.2.1.jar
    commons-io-1.3.2.jar
    源码可以去这个地址下载http://download.csdn.net/source/3187325