使用变量访问JSON值 [英] Accessing JSON values with a variable
问题描述
我正在尝试使用jQuery访问JSON数据,并基于变量获取一组特定的值.我已经在使用[]之前完成了此操作,但是由于某些原因,我无法弄清楚这次出了什么问题.
I'm trying to access JSON data with jQuery and grab a specific set of values based on a variable. I've done this before using [] but for some reason I can't figure out what is going wrong this time.
我的JSON文件(由getJSON读取,名为jsonmaker.php)如下:
My JSON file (being read in by getJSON, and named jsonmaker.php) looks like this:
{"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}}
然后我有了一个本质上是这样的函数:
I then have a function which is essentially this:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}
}
但是它总是返回未定义的.知道我在做什么错吗?我已检查以确保要分配给attrib的var是0107001,那里没有问题.
But it keeps returning undefined. Any idea what I'm doing wrong? I've checked to make sure the var going to attrib is 0107001, no problems there.
此外,我知道我的JSON文件是一个php文件,因此我可以过滤返回的内容以匹配attrib值,但是我正在寻找一种可以完全在HTML和JS上运行的东西,因此我可以打包JSON提交项目文件,并随身携带.不需要带有PHP等的Web服务器.
Also, I know my JSON file is a php file so I could filter what's returned to match the attrib value, but I'm looking to develop something that can run purely on HTML and JS, so I could just pack the JSON file for the project and take it with me. No need for a web server w/ PHP etc.
推荐答案
数据访问本身对我有用:
The data access itself works for me:
var data = {"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}};
var attrib = "0107002";
alert(data[attrib].label); // USA
请确保在您调用addAttrib()的那一刻与AJAX请求完成以及您的匿名回调函数被调用的那一刻之间,attrib
保持不变.
Make sure that attrib
remains untouched between the moment you call addAttrib() and the moment when the AJAX request completes and your anonymous callback function gets called.
更新:这是您的真实代码吗?您至少有一个语法错误:
Update: is this your real code? You have at least one syntax error:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}); // <- Please note missing ");"
}
这篇关于使用变量访问JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!