首页 文章

Ajax json POST和Spring MVC Controller

提问于
浏览
4

我有像这样的ajax json POST方法

$.ajax({
    type: 'POST',
    url: "localhost:8080/webeditor/spring/json/", 
    data: JSON.stringify(contents),
    dataType: "json"
});

控制器处理发布请求

JSONPObject json;
BindingResult result = new BeanPropertyBindingResult( json , "MyPresentation" );
@RequestMapping(value="json/", method = RequestMethod.POST)
public void savePresentationInJSON(Presentations presentation,BindingResult result) {
        //do some action

}

但是我收到了这个错误

XMLHttpRequest无法加载localhost:8080 / webeditor / spring / json / . 仅支持HTTP的跨源请求 .

我不确定如何纠正上述错误 .

6 回答

  • -1

    我的最终作品版本

    var jsonfile={json:JSON.stringify(contents)};
    $.ajax({
        type: 'POST',
        url: "/webeditor/spring/json/", 
        data: jsonfile,
        dataType: "json"
    });
    

    AJAX,和

    @RequestMapping(value = "/json/", method = RequestMethod.POST)
    public void saveNewUsers( @RequestParam ("json") String json)
    {
        System.out.println( json );
    }
    
  • 0

    用Spring传递JSON是相当简单的 . 考虑以下jQuery函数:

    function processUrlData(data, callback) {
        $.ajax({
            type: "GET",
            url: "getCannedMessageAsJson.html",
            data: data,
            dataType: "json",
            success: function(responseData, textStatus) {
                processResponse(responseData, callback);
            },
            error : function(responseData) {
                consoleDebug("  in ajax, error: " + responseData.responseText); 
            }
        });
    }
    

    现在使用以下String @Controller方法...

    @RequestMapping(value = "/getCannedMessageAsJson.html", method = RequestMethod.POST) 
    public ResponseEntity<String> getCannedMessageAsJson(String network, String status, Model model) {
    
        int messageId = service.getIpoeCannedMessageId(network, status);
        String message = service.getIpoeCannedMessage(network, status);
    
        message = message.replaceAll("\"", "&quot;");
        message = message.replaceAll("\n", "");
    
        String json = "{\"messageId\": \"" + messageId 
        + "\", \"message\": \"" + message + "\"}"; 
    
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
    }
    

    在我的情况下,请求是如此简单,我只是在控制器方法中硬连接json格式,但你可以像使用像Jackson这样的库来生成json字符串 .

    另外,正如其他人所说,验证@RequestMapping中的“值”是唯一的合法文件名 . 使用上面显示的json方法,您不必拥有相应的jsp页面(实际上它不会使用一个) .

  • 2

    在URL:url:“localhost:8080 / webeditor / spring / json /”

    webeditor必须是战争名称或服务名称所以你的@RequestMapping(值= "/webeditor/spring/json/"我认为你不应该'webeditor'它必须只有 /spring/json

    通常404表示URL请求错误或者没有为该URL运行此类服务

  • 5

    看起来像jQuery所以为什么不尝试

    $.getJSON('webeditor/spring/json', JSON.stringify(contents, function(data) {//do callbackstuff});
    

    如果您想要跨域请求的方式如下: -

    cbFn = function(data) {
       // do callback stuff. 
    }
    
        var ca = document.createElement('script');
                    ca.type = 'text/javascript';
                    ca.async = true;
                    ca.src = server + '/webeditor/spring/json.jsonp?callback=cbFn';
                    var s = document.getElementsByTagName('head')[0];
                    s.parentNode.insertBefore(ca, s);
    

    并添加servlet映射

    <servlet-mapping>
        <servlet-name>yourSevletName</servlet-name>
        <url-pattern>*.jsonp</url-pattern>
    </servlet-mapping>
    
  • 0

    您的应用程序应该有一个上下文根,它位于URL路径的其余部分之前 . 您还应该在web.xml中定义 servlet-mapping ,它定义了哪些请求被定向到您的Spring控制器 . 因此,如果您的应用程序的上下文根是"myapp"而您的 servlet-mapping 将转到* .html,那么您的ajax调用将如下所示:

    $.ajax({
        type: 'POST',
        url: "/myapp/webeditor/spring/json.html",
        data: JSON.stringify(contents),
        dataType: "json",
        success: function(response) {
            // Success Action
        }
    });
    
  • 0

    在jr中包含像这样的标记库

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    

    然后使用spring创建一个完整的URL

    <c:url var="yourFullUrl" value="/webeditor/spring/json/" />
    

    然后基于此创建javascript变量,以便您可以在Ajax中使用

    <script>
    var yourUrl= '<c:out value="${yourFullUrl}"/>';
    </script>
    

    不使用代表url的javascript变量:

    <script>
    $.ajax({
            type: 'POST',
            url: yourUrl, 
            data: JSON.stringify(contents),
            dataType: "json"
    });
    </script>
    

相关问题