jQuery Ajax请求错误404(未找到)但它的工作原理

时间:2015-12-15 12:16:00

标签: javascript java jquery ajax spring

我正在向服务器发送jQuery AJAX请求,但浏览器的控制台告诉我找不到该页面。仍然,我的Spring MVC签名映射请求的URL被执行,但AJAX函数的done部分却没有。

以下是相关代码:

使用Javascript:

    var content = $(data).filter("#wrapper-email-content");
    $.ajax({
        url : '/sendEmail',
        type : 'POST',
        data : {
            content: content.html()
        }
    }).done(function(){
        console.log("Finished")
    });

Spring MVC签名:

@RequestMapping(value = "/sendEmail", method = RequestMethod.POST)
public void sendEmail(
    HttpServletRequest request, String content) {

    UserTO user = (UserTO) request.getSession().getAttribute("USER");
    String email = user.getEmail();
    String title = "Your order";
    Email.sendEmail(title, email, content, null, null, null);
}

因此,在代码中,电子邮件被发送,这意味着执行了sendEmail方法,但我仍然得到错误404:从AJAX请求中找不到,并且“完成”未在控制台中打印。

我做错了什么?

3 个答案:

答案 0 :(得分:2)

@RequestMapping(value = "/sendEmail",headers="Accept=application/json", method = RequestMethod.POST)
public Map<String,String> sendEmail(
    HttpServletRequest request, @RequestBody String content) {
    Map<String,String> statusMap=new HashMap<String,String>();
    UserTO user = (UserTO) request.getSession().getAttribute("USER");
    String email = user.getEmail();
    String title = "Your order";
    Email.sendEmail(title, email, content, null, null, null);
    statusMap.put("status","Mail sent successfully");
    return statusMap;
}

答案 1 :(得分:1)

编辑:查看针对What to return if Spring MVC controller method doesn't return value?

发布的解决方案

不熟悉MVC Spring,但您可能需要自己返回成功状态代码:

public String sendEmail(
    HttpServletRequest request, @RequestBody String content) {

    UserTO user = (UserTO) request.getSession().getAttribute("USER");
    String email = user.getEmail();
    String title = "Your order";
    Email.sendEmail(title, email, content, null, null, null);
    return new ResponseEntity<String>(json,HttpStatus.OK);
}

答案 2 :(得分:1)

更好的解决方案是使用

注释您的方法
@ResponseStatus(value = HttpStatus.OK)

请参阅答案https://stackoverflow.com/a/12839817/954602以获取示例。