问题描述
我正在尝试将带有循环引用的对象从 node.js 服务器传递到客户端 javascript.
I'm trying to pass an object with circular references from node.js server to client-side javascript.
服务器(node.js):
Server (node.js):
var object = { circular: object }
//....
app.get('/', function(req, res){
res.render('index.jade', {object: object});
});
客户端 Jade/Javascript
Client-side Jade/Javascript
script var object = !{JSON.stringify(object)};
这里我得到了 object
包含循环引用的错误.
Here I get the error that object
contains circular references.
以任何方式在客户端 javascript 中获取 object
,使用循环引用?
Any way to get the object
in client-side javascript, withcircular references?
推荐答案
Douglas Crockford 对此有一个解决方案,我之前已经成功地使用过:Cycle.js
Douglas Crockford has a solution for this that I have successfully used to solve this problem before: Cycle.js
而不是仅仅使用 stringify
和 parse
你会首先调用 decycle
并用 retrocycle
instead of just using stringify
and parse
you would first call decycle
and restore with retrocycle
var jsonString = JSON.stringify(JSON.decycle(parent));
var restoredObject = JSON.retrocycle(JSON.parse(jsonString));
这篇关于将具有循环引用的对象从服务器传递到客户端 Javascript,同时保持循环性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!