简体   繁体   中英

How do I access this JSON data in Javascript?

{"0":
    {"id":"276","course":"92","name":"Tutorial - Compound Measures",
    "activitylink":"2490","available":"1331231400","deadline":"1331235000"},
 "1":
    "example@gmail.com","reference":"example@gmail.com"}

I am trying to access this in jQuery/Javascript but I unable to. This is my jQuery:

$('#lessonSelect').live('change', function()
{
    $.getJSON('?ajax=true&lid='+$('#lessonSelect').val(), function(data)
    {     
        var len = data.length;      
        var lessonDialog = "";//initialise
        var launchLessonDiv = '<a href="' + data.reference + '">Launch Lesson</a>';

        for (var i = 0; i< len; i++)
        {
            lessonDialog += '<p>' + data[i].name + '</p>'; //get lesson name
        }

        $('#lessonDialog').html(lessonDialog); //insert lesson name into dialog
        $('#launchLessonDiv').html(launchLessonDiv);

    });   
});

This is basically for a select list. Each time the user selects something, links and other stuff on the page change. The stuff works when the page is first loaded but when I start selecting stuff in the select list the lessonDialog comes up blank with nothing inside it.

Convert the object with numeric keys to a true array:

$.getJSON('?ajax=true&lid='+$('#lessonSelect').val(), function(data) {   
    data = Array.prototype.slice.call(data);

Your current method fails, because { ... } results in the creation of an object, not an array. The length property of the object is undefined , so the loop would never get started:

for (var i=0; i<undefined; i++) ; // <-- 0 < undefined is always false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM