jsp代码
<%--
Created by IntelliJ IDEA.
User: aside
Date: 2019/8/6
Time: 10:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="JqueryRes/Res/jquery-1.7.2.min.js"></script>
<script>
function Ajax() {
$.ajax({
type: "POST",
url: "test",
data: {name: 123},
dataType: 'text',
success: function (date) {
alert("正确数据")
alert(date)
},
error: function (date) {
alert("错误数据")
alert(date.responseText)
}
});
}
</script>
</head>
<body>
My First Jsp
<a href="test">afasf</a>
<h2 id="h2" onclick='Ajax()'>Ajax</h2>
</body>
</html>
后台代码
package com.springboot.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.http.HttpServletRequest;
@Controller
public class MainController {
@Autowired
private HttpServletRequest request;
// @RequestMapping(value = "test", method = RequestMethod.GET)
// @GetMapping("test")
@PostMapping("test")
@ResponseBody
public String test() {
// ContextLoader.getCurrentWebApplicationContext();
System.out.println(request.getParameter("name"));
System.out.println("sdfsfsf");
return "success";
}
}
原因是因为后台返回的数据格式和前台ajax中success要求的数据格式不一致导致的
上述代码中的ajax部分的 dataType: ‘text’, 配置为text,后台需要返回string
如果是json,后台需要返回json,如果不一致就会出现后台虽然处理成功但是前台走的却是error