ajax后台处理成功,前台返回不走success而是走error问题

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值