You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Controller返回JSON解析错误,求Ajax打开新页解决方案

问题分析与解决方案

问题现象

点击按钮发起Ajax POST请求后,接口返回状态码200,但前端触发parsererror,错误信息为SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data。此前尝试将URL存入session,通过window.open(URL_IN_SESSION)调用,但刷新页面会重复触发该操作,用c:remove清除变量也无效。需求是获取之前GET请求生成的自定义URL,通过Ajax或JavaScript在新标签页打开,同时保留主页面。

涉及代码

后端Controller代码

@Controller
@RequestMapping("/myHostel.html")
public class HostelController
{

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView getText()
    {
        // do some cool stuff but not the point here
    }

    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String getMyUrl()
    {
        String myVariable;
        return "{\"myUrl\": \""+myVariable+"\"}";
    }

}

前端Ajax代码

function openNewTab() {
    $.ajax({
        url : 'myHostel.html',
        type: "POST",
        dataType: "json",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Accept", "application/json");  
        },
        success : function(response){           
            console.log(response);

            window.open(response.url, '_blank');
        },
        error: function(jqXHR, exception, errorThrown)
        {
            console.log(jqXHR.status);
            console.log(exception);
            console.log(errorThrown);
        }
    });
}

按钮代码

<button tabindex="0" id="mySweetButton" class="btn btn-primary" 
    onclick="openNewTab();" >
    Open a new tab
</button>

错误原因

  1. JSON格式错误:后端手动拼接JSON字符串,且myVariable未初始化(值为null),拼接后会生成{"myUrl": "null"};如果myVariable包含特殊字符(如引号、反斜杠),还会直接破坏JSON结构,导致前端解析失败。
  2. 字段名不匹配:后端返回的JSON键是myUrl,但前端代码里取的是response.url,即使JSON解析成功也拿不到正确值。
  3. Session未及时清理:之前用session存URL时,未在使用后移除session中的变量,导致刷新页面时session里的URL仍存在,重复触发打开操作。

解决方案

后端代码优化

放弃手动拼接JSON,利用Spring内置的序列化工具自动生成合法JSON;同时在GET请求中把生成的URL存入session,POST请求取出后及时清理session,避免重复触发。

@Controller
@RequestMapping("/myHostel.html")
public class HostelController {

    @GetMapping
    public ModelAndView getText(HttpSession session) {
        // 替换为你生成自定义URL的实际逻辑
        String customUrl = "https://your-custom-url.com/path";
        // 将URL存入session
        session.setAttribute("customUrl", customUrl);
        return new ModelAndView("your-view-name"); // 替换为你的实际视图名
    }

    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, String> getMyUrl(HttpSession session) {
        // 从session中取出之前生成的URL
        String myVariable = (String) session.getAttribute("customUrl");
        // 用Map封装返回结果,Spring会自动转成合法JSON
        Map<String, String> responseMap = new HashMap<>();
        responseMap.put("myUrl", myVariable);
        
        // 用完后移除session中的URL,避免刷新页面重复触发
        session.removeAttribute("customUrl");
        
        return responseMap;
    }
}

前端代码修正

修正字段名匹配问题,同时简化请求头设置(jQuery指定dataType: "json"后会自动设置Accept头):

function openNewTab() {
    $.ajax({
        url: 'myHostel.html',
        type: "POST",
        dataType: "json",
        success: function(response) {           
            console.log(response);
            // 匹配后端返回的键名myUrl
            if (response.myUrl) {
                window.open(response.myUrl, '_blank');
            }
        },
        error: function(jqXHR, exception, errorThrown) {
            console.log(jqXHR.status);
            console.log(exception);
            console.log(errorThrown);
        }
    });
}

内容的提问来源于stack exchange,提问作者Noxaeternae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:35:21