我有如下... chrome
chrome.extension.sendRequest({ req: "getDocument", docu: pagedoc, name: 'name' }, function(response){ var efjs = response.reply; });
該調用如下。 npm
case "getBrowserForDocumentAttribute": alert("ZOMG HERE"); sendResponse({ reply: getBrowserForDocumentAttribute(request.docu,request.name) }); break;
可是,個人代碼永遠不會到達「 ZOMG HERE」,而是在運行chrome.extension.sendRequest
拋出如下錯誤 json
Uncaught TypeError: Converting circular structure to JSON chromeHidden.JSON.stringify chrome.Port.postMessage chrome.initExtension.chrome.extension.sendRequest suggestQuery
有誰知道是什麼緣由形成的? 函數
一種方法是從主要對象中剝離對象和功能。 並簡化表格 post
function simpleStringify (object){ var simpleObject = {}; for (var prop in object ){ if (!object.hasOwnProperty(prop)){ continue; } if (typeof(object[prop]) == 'object'){ continue; } if (typeof(object[prop]) == 'function'){ continue; } simpleObject[prop] = object[prop]; } return JSON.stringify(simpleObject); // returns cleaned up JSON };
我像這樣在NodeJS上解決了這個問題: ui
var util = require('util'); // Our circular object var obj = {foo: {bar: null}, a:{a:{a:{a:{a:{a:{a:{hi: 'Yo!'}}}}}}}}; obj.foo.bar = obj; // Generate almost valid JS object definition code (typeof string) var str = util.inspect(b, {depth: null}); // Fix code to the valid state (in this example it is not required, but my object was huge and complex, and I needed this for my case) str = str .replace(/<Buffer[ \w\.]+>/ig, '"buffer"') .replace(/\[Function]/ig, 'function(){}') .replace(/\[Circular]/ig, '"Circular"') .replace(/\{ \[Function: ([\w]+)]/ig, '{ $1: function $1 () {},') .replace(/\[Function: ([\w]+)]/ig, 'function $1(){}') .replace(/(\w+): ([\w :]+GMT\+[\w \(\)]+),/ig, '$1: new Date("$2"),') .replace(/(\S+): ,/ig, '$1: null,'); // Create function to eval stringifyed code var foo = new Function('return ' + str + ';'); // And have fun console.log(JSON.stringify(foo(), null, 4));
這可能不是相關的答案,可是此連接檢測並修復JavaScript中的循環引用可能有助於檢測致使循環依賴性的對象 。 this
我一般使用circular-json npm包來解決此問題。 spa
// Felix Kling's example var a = {}; a.b = a; // load circular-json module var CircularJSON = require('circular-json'); console.log(CircularJSON.stringify(a)); //result {"b":"~"}
注意:circular-json已被棄用,我如今使用flatted(來自CircularJSON的建立者): code
// ESM import {parse, stringify} from 'flatted/esm'; // CJS const {parse, stringify} = require('flatted/cjs'); const a = [{}]; a[0].a = a; a.push(a); stringify(a); // [["1","0"],{"a":"0"}]
來自: https : //www.npmjs.com/package/flatted orm
我在使用jQuery formvaliadator時遇到了一樣的錯誤,可是當我在success:函數中刪除console.log時,它起做用了。