2016-03-05 86 views
0

我目前正在使用fullCalendar(jQuery插件),现在仍然陷入愚蠢的问题,但我无法克服它。将json从Action类中转换为ajax

尝试在日历页面加载时从数据库填充事件详细信息。这里是我的代码,

$('#calendar').fullCalendar({ 
      defaultDate: '2016-03-12', 
      editable: true, 
      eventLimit: true, // allow "more" link when too many events 
      eventSources: [ 
        getEvents() 
        ] 
     }); 

     function getEvents(){ 
      alert("Inside get Events"); 

      $.ajax({ 
       url : "/FullCal/eventDetails.do", 
       dataType : 'json', 
       success : function(data){ 
        alert(data) 
       } 
      }); 
     } 

正在使用Struts框架,这里是我的动作映射,

<action path="/eventDetails" type="com.struts.action.CalendarInviteAction" > 
      <forward name="success" path="/Calendar.jsp" /> 
     </action> 

我的动作类有JSON格式的事件细节数据。我的问题是如何将json数据写入ajax响应(简单来说,如何将json数据返回给ajax调用)。这里是我的动作类修订

public ActionForward execute(ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response) throws Exception{ 

     System.out.println("TEsting inside getEventDetails"); 

     ArrayList<EventForm> arr = new ArrayList<EventForm>(); 

     arr.add(new EventForm("HandOff Meeting" , new Date(), new Date(),"Meeting at HandOffBridge")); 

     Gson gson = new Gson(); 
     String jsonString = gson.toJson(arr); 

     response.getWriter().write(jsonString); 

     return null; 
    } 

jsonString包含JSON格式eventDetails,怎么这回阿贾克斯。

请帮我实现这一点。

回答

1

你的Ajax调用似乎罚款。只需要以适当的方式显示ajax响应。

events: function(start, end, timezone, callback) { 
    $.ajax({ 
    url : "/FullCal/eventDetails.do", 
    dataType : 'json', 
    success : function(data){ 
     callback(data); 
    } 
    }); 
} 
1

A dataType : 'json'被[jQuery Ajax] [1]用于指定数据类型,该数据类型在执行操作和结果时将返回success回调函数,并返回从服务器返回的响应。

dataType(默认:智能猜测(xmljsonscript,或html))

类型:String

的类型,你期望从服务器返回的数据。如果没有指定,jQuery将尝试根据响应的MIME类型推断它(XML MIME类型将生成XML,在1.4中JSON将生成一个JavaScript对象,在1.4脚本中将执行该脚本,而其他任何东西都将作为字符串返回)。

该URL应该正确指向动作映射。假设它将在默认名称空间中,否则您应该修改URL和映射以添加namespace属性。

<script type="text/javascript"> 
    $(function() { 
    $("#dialog-form").dialog ({ 
     autoOpen: true, 
     height: 500, 
     width: 750, 
     modal: true, 
     buttons : { 
     "Search" : function() { 
      $.ajax({ 
      url : '<s:url action="part" />', 
      success : function(data) { 
       //var obj = $.parseJSON(data); 
       var obj = data; 
       alert(JSON.stringify(obj)); 
      } 
      }); 
     } 
     } 
    }); 
    }); 
</script> 
+0

感谢您的回应Kishnan。我已在帖子中更新了我的操作类代码。我想将jsonString返回给ajax。请看看并帮助我。 – Krupa

+0

我已添加新的答案,请尝试语法代码。,谢谢 –

+0

感谢您的回复。我想从Action类返回字符串到ajax调用。基于我的理解,如果我使用的数据,你刚才提到它只是添加到ajax请求。如果错误请更正 – Krupa

0

我的第一个猜测是为什么返回null?

return null; 

只返回JSON字符串:

return jsonString; 
+0

由于这是一个ajax调用,只需返回null以便struts不会采取任何进一步的操作。 – Krupa