javascript 将 json 分配给变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16238619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assigning json to variable
提问by LarsVegas
Ok, some explanation. Even though I don't think it has anything to do with the problem itself. I have a small django project that maps some data using leaflet. On a mouseover some ajax functionality is added, using the dajax
(which is a "lightweight library to implement AJAX inside django projects") framework. The call itself looks like this:
好的,一些解释。尽管我认为这与问题本身没有任何关系。我有一个使用传单映射一些数据的小型 django 项目。在鼠标悬停时添加了一些 ajax 功能,使用dajax
(这是一个“在 django 项目中实现 AJAX 的轻量级库”)框架。调用本身如下所示:
dajax.add_data(simplejson.dumps(series), 'my_test_flot')
My js function receives json data which looks like this (using alert
)
我的 js 函数接收如下所示的 json 数据(使用alert
)
[{"color": "#dddd00",
"data": [[-0.5, -20.5]],
"label": "Tweede Zandlaag"}]
The object has more data to it but the problem is not with the object. When I copy/paste the data directly into the function var series = []
the behaviour is as aspected. As aspected means, the graph I'm drawing with flot
is actually being drawn. Otherwise the graph remains empty.
对象有更多数据,但问题不在于对象。当我将数据直接复制/粘贴到函数中时var series = []
,行为是方面的。作为方面的意思,我正在绘制的图形flot
实际上正在绘制。否则图形保持为空。
function my_test_flot(dat) {
function MyFormatter(v, xaxis) {
return " ";
}
$(function () {
alert(dat)
var series = dat; // here lies the problem, but why?
...
Can anyone help?
任何人都可以帮忙吗?
回答by LarsVegas
回答by Alexander Gessler
This does not copy the data - it just makes series
a reference to the same object as dat
. Therefore, if you later modify the object, all users retaining references to it see the changes. This is probably what causes your trouble.
这不会复制数据 - 它只是series
引用与dat
. 因此,如果您稍后修改该对象,所有保留对它的引用的用户都会看到更改。这可能是导致您遇到麻烦的原因。