要解析的有效JSON或JavaScript对象
Valid JSON or JavaScript object to parse
我有一个很长的轮询操作,将新对象作为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.
值的定义相关文章:
- Chrome开发工具(如何知道我在调用哪个javascript对象)
- 循环遍历以数组为值的Javascript对象
- 从ajax请求中获取javascript对象
- 如何从对象的原型方法访问JavaScript对象属性
- 将XML转换为普通的旧JavaScript对象
- 通过引用传递JavaScript对象
- javascript对象操作:根据指定条件选择属性
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 如何在异步函数中使用javascript对象
- 临时Javascript对象
- 如何在ASP中为用户控件添加Javascript对象网
- 使用数组向下搜索Javascript对象
- Rails将JavaScript对象存储到Model的有效方式
- JavaScript对象不是从原型链继承的
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- SetInterval在javascript对象中表现怪异
- Javascript 对象和 this 关键字
- 如何在不知道关键字的情况下访问javascript对象值
- 在 JavaScript 对象中设置要使用的运算符的属性
- 如何搜索JavaScript对象并更改值