向json查询添加一个变量

时间:2021-07-02 17:01:51

I have this piece of code:

我有这段代码:

[...]
var apiURL = "http://.../api.php?format=json";
$.getJSON(apiURL, function(jsonData) {
   $('#tr<?php echo $itemId; ?>').text( $(jsonData)[0].query.pages. + objId  );
});
[...]

Where objId is a javascript variable that can handle different values. How can I make this working? How can I add a variable to this json query?

objId是一个javascript变量,可以处理不同的值。我如何让它工作?如何向这个json查询添加一个变量?

The json is this one:

json是这个:

{
    "query": {
        "pages": {
            "6": {
                "pageid": 6,
                "ns": 0,
                "title": ".ODk.MTc5",
                "touched": "2013-05-03T10:22:37Z",
                "lastrevid": 26,
                "counter": 0,
                "length": 23,
                "new": "",
                "protection": [{
                        "type": "edit",
                        "level": "sysop",
                        "expiry": "infinity"
                    }
                ]
            }
        }
    }
}

Thanks!

谢谢!

1 个解决方案

#1


1  

Here's what you need to do:

你需要做的是:

var apiURL = "http://.../api.php?format=json";
$.getJSON(apiURL, function(jsonData) {
   $('#tr<?php echo $itemId; ?>').text( jsonData.query.pages[objId]  );
});

jsonData is a valid JavaScript object, so you can just access its properties with either dot notation or bracket notation. Bracket notation takes in a string or integer (which is what I assume objId would be) and looks up the property based on that. Dot notation does what you'd expect from any object. There's no reason to try to create a jQuery object out of it first, since that would just not select anything.

jsonData是一个有效的JavaScript对象,因此您可以使用点表示法或方括号表示法访问它的属性。括号表示法采用字符串或整数(我认为这是objId),并基于此查找属性。点表示法可以实现任何对象的期望。没有理由先从jQuery中创建一个jQuery对象,因为它不会选择任何内容。

#1


1  

Here's what you need to do:

你需要做的是:

var apiURL = "http://.../api.php?format=json";
$.getJSON(apiURL, function(jsonData) {
   $('#tr<?php echo $itemId; ?>').text( jsonData.query.pages[objId]  );
});

jsonData is a valid JavaScript object, so you can just access its properties with either dot notation or bracket notation. Bracket notation takes in a string or integer (which is what I assume objId would be) and looks up the property based on that. Dot notation does what you'd expect from any object. There's no reason to try to create a jQuery object out of it first, since that would just not select anything.

jsonData是一个有效的JavaScript对象,因此您可以使用点表示法或方括号表示法访问它的属性。括号表示法采用字符串或整数(我认为这是objId),并基于此查找属性。点表示法可以实现任何对象的期望。没有理由先从jQuery中创建一个jQuery对象,因为它不会选择任何内容。