Ajax调用失败并重新加载页面

时间:2014-05-08 18:21:58

标签: java javascript jquery ajax

我有一个Ajax调用,它会将一些JSON发送到db中。但是当ajax被触发时,它只会刷新页面而不会插入任何内容。没有显示错误消息。

Ajax方法

 function send_track(track) {
            var mainpath = "<%=request.getContextPath()%>";
            var json = JSON.stringify(track);
            var url = mainpath + '/API/Track/Update';                

            $.ajax({
                type: "PUT",
                contentType: 'application/json; charset=utf-8',
                url: url,
                data: json,
                statusCode: {
                    200 : function() {
                        $('#messagePlaceholder').html('<div class="alert alert-success alert-dismissable">' +
                                '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' +
                                '<strong><fmt:message key="error.success" />: </strong><fmt:message key="error.track.saved" /></div>');
                    },
                    400 : function() {
                        $('#messagePlaceholder').html('<div class="alert alert-danger alert-dismissable">' +
                                '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' +
                                '<strong><fmt:message key="error.error" />: </strong><fmt:message key="error.track.notsaved" /></div>');
                    }
                }

            });
        }

创建方法

@PUT
@Path("/Create")
@Consumes(MediaType.APPLICATION_JSON)
public Response Create(@Context HttpServletRequest request, TrackVM track) {
    try {
        HttpSession s = request.getSession();
        if (s.getAttribute("User") == null) {
            throw new Exception("Not logged in");
        }

        User u = (User) s.getAttribute("User");
        track.setUserID(u.getID());
        int trackID = _trackDao.AddTrack(track.Convert());

        if (!AddTiles(track.getTiles(), trackID)) {
            _trackDao.DeleteTrack(trackID);
            throw new Exception("Tiles not added");
        }
        return Response.status(Response.Status.OK).build();
    } catch (Exception e) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}

当我在Create方法中放置一个断点并在调试模式下运行它时,它会将数据插入db。

修改

启动事件的按钮

<button id="saveButton" class="btn btn-default btn-lg" onclick="save_track()"> <span class="glyphicon glyphicon-floppy-save"></span> <fmt:message key="text.save" /></button>

save_track()填写track对象并将其发送到send_track()

1 个答案:

答案 0 :(得分:0)

通过POST更改请求方法PUT

$.ajax({
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    url: url,
                    data: json,
                    statusCode: {