繁体   English   中英

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 (即使true也不可行-我猜这里的jQuery源中存在不一致的地方)。

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

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

要么

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

工作实例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM