2016-05-12 42 views
1

我想转换点击信息进行存储JSON转换点击信息,以JSON

$(document).click(function(e){ 
    url = '/recordclick'; 
    $.post(url, {'clickData':JSON.stringify(e)}); 
}); 

但似乎click事件中有一个或多个循环引用,因为我得到的错误

Uncaught TypeError: Converting circular structure to JSON

有没有方法可以轻松地将点击事件转换为没有循环引用的东西,也就是说,不需要手动删除每个循环引用属性?

+0

不要这样做。事实上你需要什么部分? – SLaks

+0

为什么你需要将这样的大事件对象串入json中? – MarkoCen

+0

为什么不只是创建一个只有你需要的东西的对象,然后做JSON.stringify –

回答

2

您可以使用道格拉斯Crockford的JSON.decycle功能,它编码为JSON之前,在事件对象的深层副本。

周守军代码在这里:https://github.com/douglascrockford/JSON-js/blob/master/cycle.js

这里是从功能的描述源代码的报价

Make a deep copy of an object or array, assuring that there is at most one instance of each object or array in the resulting structure. The duplicate references (which might be forming cycles) are replaced with an object of the form {"$ref": PATH} where the PATH is a JSONPath string that locates the first occurance. [...]

正如您所包含JSON.decycle你的代码可以这样调整:

$(document).click(function(e) { 
    var url = '/recordclick', // let's declare variables as local! 
     dec = JSON.decycle(e); 
    $.post(url, { 'clickData': JSON.stringify(dec) }); 
}); 
1

stringify函数接受一个过滤函数作为第二个参数,所以我认为你可以做到这一点。

JSON.stringify(event, function(key, value) { 
    if(key == 'circularReference1' || key == 'circularReference2') { return value.id;} 
    else {return value;} 
} 
+0

这假设我有一个循环引用的列表('circularReference1','circularReference2'等),是否正确? – wogsland

+0

的确,您可以通过检查事件对象轻松获取列表,主要是在像父母等事件中引用的DOM元素。 –