2

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?

The json is this one:

{
    "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!

3
  • 2
    Why are you passing JSON string to $? Commented May 7, 2013 at 14:54
  • 1
    "How can I make this working?" What exactly is not working? Commented May 7, 2013 at 14:56
  • just jsonData["query"]["pages"][objId] or jsonData.query.pages[objId] Commented May 7, 2013 at 15:25

1 Answer 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.