jQuery ajax 使用 .html() 处理响应

jQuery ajax handle response with .html()

我的 Java 控制器从表单中获取数据并发回 JSON 布尔结果:

@RequestMapping(value = "/person/save", ... )
@ResponseBody
public boolean savePerson(...) {
    ...
    return jpaPersonService.savePersonService(person);
}

表单提交按钮上的 JS:

$('#savePersonForm').submit(function (event) {
    event.preventDefault();
    $.ajax({
        url: '/person/save',
        type: 'post',
        data: $('#savePersonForm').serialize(),
        success: function (response, textStatus, jqXHR) {
            console.log("ajax success");
            console.log("response: " + response);
            $('#result').html(response);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('error(s):' + textStatus, errorThrown);
        }
    });
});

在这两种情况下,当我的控制器发回 true/false 时,我可以看到 response: trueresponse: false。所以我确定 JS 会得到答案。

我的下一步是将此答案添加到 div #result 中。如果是 true - 一切都很好。如果它是 false,我得到一个空的 div。经过一些测试后,我发现如果我向 response 添加文本,它会起作用:$('#result').html(response + '');.
我正在使用 jquery-2.1.4.min.js.

我是不是哪里弄错了,或者应该是这样的?谢谢。

问题是因为您试图将元素的 html() 设置为 false 布尔值 doesn't work(尽管 true 确实如此 - 我猜这里的 jQuery 来源不一致。

要解决此问题,您需要强制将布尔类型强制转换为字符串。试试这个:

$('#result').html('' + response);

$('#result').html(response.toString()); // if supported

Working example