如何使用jquery和json访问特定的json对象? [英] How can I access a specific json object using jquery and json?
问题描述
我在尝试使用jQuery和JSON返回特定记录时遇到问题.我正在将一个变量传递给该函数,并且只希望输出与执行该函数时设置的ID匹配的数据.
I'm having a problem trying to return a specific record using jQuery and JSON. I'm passing a variable to the function and want to output only the data matching the id I've set when the function is executed.
现在,我的功能如下:
function getEffectsData(myNum){
$.getJSON("jsonscript.php", { id: +myNum },function(data){
var x = data.x;
//DO SOME STUFF
});
}
JSON输出如下:
{"stuff": [ { "id":1, "x":3, "y":6, "z":-6 },{ "id":2, "x":2, "y":7, "z":-3 }]}
我唯一知道的是正确的变量正在传递给函数.在那之后,什么都没有发生.这是非常新的,因此,非常感谢您的帮助.
The only thing I know is that the correct variable is being passed to the function. After that, nothing happens. Very new at this, so any help is greatly appreciated.
感谢大家对此的投入.为了澄清,我试图仅从id与myNum匹配的对象返回数据.我希望能够访问该对象中的所有数据,但只能访问该对象.我不知道该对象将在数组中的哪个位置.我简化了问题中的ID和数据,以帮助澄清问题.
I appreciate everybody's input on this. To clarify, I am trying to return the data from only the object that's id matches myNum. I want to be able to access all of the data from that object, but only that object. I have no idea where that object will be in the array. I simplified the ids and the data in my question to help clarify the problem.
再次感谢.
推荐答案
您可以像这样从JSON访问x:
You can access x from your JSON like this:
var x1 = data.stuff[0].x; // the first object's x key
var x2 = data.stuff[1].x; // the second object's x key
因为您的JSON树如下所示:
Because your JSON tree looks like this:
{ // base object
"stuff": [ // array
{ // 0.: object
"id": 1, // key => value
"x" : 3, // key => value
"y" : 6, // key => value
"z" : -6 // key => value
},
{ // 1.: object
"id": 2, // key => value
"x" : 2, // key => value
"y" : 7, // key => value
"z" : -3 // key => value
}]
}
因此,在data.stuff[0].x
中选择stuff
对象,然后选择first
元素,然后选择其x
键.
So with data.stuff[0].x
you select stuff
object then it's first
element and then its x
key.
但是,例如,如果要处理所有x
键,则需要通过简单的for
循环或
But If you want to handle all the x
key for example, then you need to loop through the stuff
array by a simple for
loop or the $.each
method.
更新
关于您的问题.如果要获取ID为myNum
的对象,则有 2种可能性:
As for your question. If you want to get the object with id myNum
you have 2 possibilities:
if you possess
jsonscript.php
you can send the data only with the correct id from the server, because you pass the id to it by{ id: +myNum }
which is the second parameter ofgetJSON
您将遍历数据,直到找到具有正确ID的对象
You loop through the data until you find the object with the correct id
var object;
$.each(data.stuff, function(i, obj) {
if (obj.id === myNum) object = obj;
});
// now object is the one with the right id
这篇关于如何使用jquery和json访问特定的json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!