【问题标题】:404 Not Found in AJAX post call404 Not Found in AJAX post call
【发布时间】:2019-04-06 22:42:25
【问题描述】:

我正在使用 Spring MVC,当我执行 ajax 后调用时,我得到一个 404。我的控制器如下所示:

@Controller
@RequestMapping("/mensaje")
public class MensajeController {

    public MensajeController() {
        super();
    }

    @ResponseBody
    @RequestMapping(value = "/prueba", method = RequestMethod.POST)
    public String prueba(@RequestParam("cuerpo") final String cuerpo) {
        String b = null;

        String a = null;

        return b;
    }
}

还有这样的 ajax 调用:

<script type='text/javascript'>
    $(document).ready(function() {      
        $("#save").click(function(e) {
            e.preventDefault();
            var myEditor = document.querySelector('#editor');
            var html = myEditor.children[0].innerHTML;

            $.ajax({
                    type : "POST",
                    url : "/Gestion-Practicas/mensaje/prueba",
                    dataType: "json",
                    contentType: 'application/json; charset=utf-8',
                    data: {'cuerpo': html},
                    async: false,
                    cache: false,
                    delay: 15,
                    success: function(data){
                        alert('success');
                    },
                    error: function (xhr) {
                        alert(xhr.responseText);
                    }
                });     
        });

    });
</script>

我进行 ajax 调用的网址是:

http://localhost:8080/Gestion-Practicas/mensaje/create.do

执行ajax调用后出现在Chrome控制台中的url是:

http://localhost:8080/Gestion-Practicas/mensaje/prueba

总结一下,ajax调用从来没有到达控制器的方法,我也不知道为什么

【问题讨论】:

    标签: javascript java jquery ajax spring-mvc


    【解决方案1】:

    而不是@RequestParam 使用@RequestBody

    @RequestParam - 用于请求url中的查询参数。

    @RequestBody - 这是一个帖子正文有效负载。

    将您的String cuerpo 转换为具有String cuerpo 属性的类

    public class PostBody{
      private String cuerpo;
      public String getCuerpo(){
        return this.cuerpo;
       }
    
       public void setCuerpo(String cuerpo){
         this.cuerpo = cuerpo;
       }
    }
    

    现在你的线public String prueba(@RequestParam("cuerpo") final String cuerpo)

    更新后看起来像public String prueba(@RequestBody final PostBody postBody)。

    【讨论】:

    • 这样做有什么意义?我是否必须为要通过 ajax 发送的每个对象创建一个不同的类?我试过了,但还是不行,因为问题是没有达到控制器的方法
    • 只看控制器代码,看起来还不错。您使用的是哪个版本的 spring。
    • 我使用的是 Spring 4.0.3
    • 你在哪里配置 Gestion-Practicas 命名空间。从控制器看来,/mensaje/prueba 是正确的 url。
    • Gestion-Practicas 是项目的名称,它被配置为添加到 url 的根目录。我也试过/mensaje/prueba 和mensaje/prueba 但结果是一样的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多