要解析的有效JSON或JavaScript对象

Valid JSON or JavaScript object to parse

本文关键字:JavaScript 对象 JSON 有效      更新时间:2023-09-26

我有一个很长的轮询操作,将新对象作为JSON发布,但是在获得返回对象的更新时,似乎有一个无效的JavaScript对象,我无法用jQuery解析,因为它不是有效的JavaScript对象,我无法到达。以下是我通过更新获得的console.log:

{'body': 'hello world', 'html': ''n<div class="message" id="md1f1cdab-3c3a-4dfe-b268-834aa9981dec"><b>burakdede: </b>hello world</div>'n', 'from': 'burakdede', 'id': 'd1f1cdab-3c3a-4dfe-b268-834aa9981dec'}

在响应出来之前,我使用eval("(" + response + ")")将其转换为JavaScript对象。show消息用于发布新消息和获取更新。它可以很好地处理新帖子,但是当响应出来时,它会给出一个错误。

var updater = {
    errorSleepTime: 500,
    poll: function() {
        var args = {"_xsrf": getCookie("_xsrf")};
        args.listing_id = $(".action").attr("id");
        $.ajax({url: "/a/message/updates", type: "POST", dataType: "text",
                data: $.param(args), success: updater.onSuccess,
                error: updater.onError});
    },
    onSuccess: function(response) {
        try {
            updater.newMessages(eval("(" + response + ")"));
        } catch (e) {
            updater.onError();
            return;
        }
        updater.errorSleepTime = 500;
        window.setTimeout(updater.poll, 0);
    },
    onError: function(response) {
        updater.errorSleepTime *= 2;
        console.log("Poll error; sleeping for", updater.errorSleepTime, "ms");
        window.setTimeout(updater.poll, updater.errorSleepTime);
    },
    newMessages: function(response) {
        if (!response.messages) return;
        var messages = response.messages;
        //console.log(messages.length, "new messages, message is :", messages);
        updater.showMessage(messages);
    },
    showMessage: function(message) {
        var existing = $("#m" + message.id);
        if (existing.length > 0)return;
        var node = $(message.html);
        node.hide();
        $("#inbox").append(node);
        node.slideDown();
    },
};
function newMessage(form) {
    var message = form.formToDict();
    var disabled = form.find("input[type=submit]");
    disabled.disable();
    $.postJSON("/a/message/new", message, function(response) {
        updater.showMessage(response);
        if (message.id) {
            form.parent().remove();
        } else {
            form.find("input[type=text]").val("").select();
            disabled.enable();
        }
    });
}

不是在客户端修复,我修复了服务器端代码,现在它正在工作。问题是它不能生成正确的JSON。

指定dataType = 'json'而不是'text'。jQuery将为您处理无效的响应。

JSON对象属性需要用双引号包装才能有效。查看http://json.org.

值的定义