使用Spring MVC的JQuery完整日历..无法调用控制器来获取JSON对象

时间:2012-04-14 13:43:39

标签: jquery json spring-mvc fullcalendar

我正在尝试使用JQuery Full Calendar以及Spring MVC + Freemarker。

我做了一个类似that的演示。

目标:我需要调用控制器来获取包含要在日历上呈现的事件的JSON对象。

问题: 我有以下freemarker它应该去控制器并获取JSON对象进行渲染,但它不会去?!!

Freemarker的:

[#ftl /]

<script type="text/javascript">
    $(document).ready(function() {

        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();

        var calendar = $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            selectable: true,
            selectHelper: true,
            select: function(start, end, allDay) {
                var title = prompt('Event Title:');
                if (title) {
                    calendar.fullCalendar('renderEvent',
                    {
                        title: title,
                        start: start,
                        end: end,
                        allDay: allDay
                    },
                            true // make the event "stick"
                            );
                }
                calendar.fullCalendar('unselect');
            },
            editable: true,
            events: [
                {
                    url: '[@spring.url '/vacation/getVacation'/]',
                    type: 'GET',

                    data: {
                        start: 'start',
                        id: 'id',
                        title: 'title'
                    }

                }
            ]
        });

    });

body {
    margin-top: 40px;
    text-align: center;
    font-size: 14px;
    font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
}

#calendar {
    width: 900px;
    margin: 0 auto;
}

控制器:

@RequestMapping(value = "/vacation/getVacation", method = RequestMethod.GET)
    public @ResponseBody   void getVacation(HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", 111);
        map.put("title", "event1");
        map.put("start", "2011-07-28");
        map.put("url", "http://yahoo.com/");

        // Convert to JSON string.
        String json = new Gson().toJson(map);


        // Write JSON string.
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().write(json);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
萤火虫射击: enter image description here

2 个答案:

答案 0 :(得分:3)

最后,我让它工作:) 我使用$ .getJSON来获取json对象。

FreeMarker的:

   $(document).ready(function() {
            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();
          $.getJSON('[@spring.url '/vacation/getVacation'/]', function (data) {
            var calendar = $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                selectable: true,
                selectHelper: true,
                select: function(start, end, allDay) {
                    var title = prompt('Event Title:');
                    if (title) {
                        calendar.fullCalendar('renderEvent',
                        {
                            title: title,
                            start: start,
                            end: end,
                            allDay: allDay
                        },
                                true // make the event "stick"
                                );
                    }
                    calendar.fullCalendar('unselect');
                },
                editable: true,
                events:[data]
            });
         });
        });

Java控制器:

@RequestMapping(value = "/vacation/getVacation", method = RequestMethod.GET)
    public
    @ResponseBody
    String getVacation(HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", 111);
        map.put("title", "event1");
        map.put("start", "2012-4-15");
        map.put("url", "http://yahoo.com/");

        // Convert to JSON string.
        String json = new Gson().toJson(map);

        // Write JSON string.
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        return json;
    }

答案 1 :(得分:0)

@RequestMapping(value = "/vacation/getVacation", method = RequestMethod.GET)
    @ResponseBody
    public String getVacation(HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", 111);
        map.put("title", "event1");
        map.put("start", "2011-07-28");
        map.put("url", "http://yahoo.com/");

        // Convert to JSON string.
        String json = new Gson().toJson(map);


        // Write JSON string.
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        return json; //Try simply returning the json
    }

根据春季文件: @ResponseBody注释类似于@RequestBody。可以将此注释放在方法上,并指示返回类型应直接写入HTTP响应主体(而不是放在模型中,或解释为视图名称)。

例如:

@RequestMapping(value = "/something", method = RequestMethod.PUT)
@ResponseBody
public String helloWorld()  {
  return "Hello World";
}

我不确定这是否与以下不同:

response.getWriter().write(json);

这篇文章讨论了差异,其中一个解决方案提到了与freemarker的冲突:Does spring mvc have response.write to output to the browser directly?

同时尝试指定ajax调用中预期的dataType:

$(document).ready(function () {
     var calendar = $('#calendar').fullCalendar({
         editable: true,
         eventSources: [{
         // your event source
             url: '[@spring.url '/vacation/getVacation'/]', // I was expecting here to call the controller,but nothing is happened !!
             type: 'GET',
             data: {
                 start: 'start',
                 id: 'id',
                 title: 'title,'
             },
             error: function () {
                 alert('there was an error while fetching events!');
             },
             color: 'yellow',
             textColor: 'black',
             dataType: 'json'
         }])
     };)
 };

正如所建议的,我还会在调试模式下运行您的应用程序,在控制器中设置一个调试点,以查看代码是否被命中。如果它没有用firebug分析你的请求中使用的url。

检查spring用于设置调度程序的配置文件。通常,在此配置中注册InternalResourceViewResolver。以下是我的一个例子:

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

如果您发现此配置,请确保它指向您存储jsp文件的区域。

我从你的评论中注意到另一件事。你说萤火虫表明你试图打这个网址:

:eventSources:[{//你的事件源url:'/ springway / vacation / getVacation',输入:'GET',数据:{start:'start',id:'id',title:'title, '}

我不喜欢格式化的方式,特别是它包含注释,这可能会使该行的其余部分无意义或在URL中使用。我会用firebug中的网络面板来看这个,它显示了通过网络的请求。这将显示您尝试击中的真实网址。

我也会在你的js中编辑这一行:

url: '[@spring.url '/vacation/getVacation'/]',

为:

url: '/vacation/getVacation',

我对@ spring.url并不熟悉,但在我看来,目前弊大于利。