带有Spring的$.getJSON未执行回调

$.getJSON With Spring Not Executing Callback

本文关键字:执行 回调 getJSON Spring 带有      更新时间:2023-09-26

我四处查看了一段时间,发现了许多类似的问题,但都没有帮助。我有一个getJSON调用,它调用我的Spring控制器,并用JSON文本进行响应(已验证是否确实返回了JSON文本),但从未执行回调(基于回调函数中没有执行任何内容,并且我没有收到错误的JavaScript)。

在我的jsp文件中:

function getUserText(str)
{
    $.getJSON("selectUser.htm", { id: str }, function(user)
    {
        //Doesn't matter what's here
    });
}

在我的控制器中:

@RequestMapping(value="/selectUser.htm")
public @ResponseBody String SelectUser(@RequestParam String id)
{
    Users user = userMap.get(id);
    if (user == null)
        return null;
    return createUserJSON(user);
}

我对此不确定,但我猜测您提供的函数是ajax返回时调用的成功函数。请求可能未成功返回。

这意味着JSON无效。可能是内容无效或内容类型设置不正确。。。。

$.getJSON has no error callback
http://api.jquery.com/jQuery.getJSON/

要了解问题出在哪里,您需要使用

$.ajax({
  url: "myurl",
  type: "GET",
  dataType: "json",
  success: function() {
    //called when successful
  },
  error: function(e) {
    //called when there is an error
  },
});

找到了答案。事实证明JSON需要是有效的。我犯了一个错误,所以JSON的格式不正确。甚至在回调函数出现之前,我就不知道格式有多重要。