2012-03-08 73 views
1

我想讓我的$ .getJSON工作,但它什麼都不返回。這裏是我的jQuery:

$('#courseSelect').bind('change', function() 
{ 
    data = $.getJSON('lessons.js'); 
    var html ='<select name="lessonSelect id="lessonSelect">'; 
    var len = data.length; 
    alert(data.length); //this alerts "undefined" 
    for (var i = 0; i< len; i++) { 
     html += '<option value="' + data[i].value + '">' + data[i].name + '</option>'; 
    } 
    html +='</select>'; 
    alert(html); //this alerts <select...></select> 
    //but no option tags because there's nothing to loop through 
    $('lessonsDiv').html(html); 
}); 

這是我lessons.js文件

{"lessons": 
    [ 
      {"value": "1", "name": "Lesson 1"}, 
      {"value": "2", "name": "Lesson 2"}, 
      {"value": "3", "name": "Three"} 
    ] 
    } 

最後,我想要做的是首先選擇課程時創建的教訓新的選擇列表。但現在,我只是想讓getJSON方法起作用,但事實並非如此。如果有人能看到有什麼問題,那就太好了。它是否期待着一種不同的數據?

回答

6

致電getJSON()是asyncho;結果不能立即提供。從getJSON()返回的是​​對象,該對象監視異步請求的狀態。

您需要註冊回調(這是第二個參數的用途),該回調在之後執行響應可用。正在處理異步請求的jqXHR對象將在請求成功完成後自動執行回調。

$('#courseSelect').bind('change', function() { 
    $.getJSON('lessons.js', function(data) { 
     var html = '<select name="lessonSelect id="lessonSelect">'; 
     var len = data.length; 
     alert(data.length); //this alerts "undefined" 
     for (var i = 0; i < len; i++) { 
      html += '<option value="' + data[i].value + '">' + data[i].name + '</option>'; 
     } 
     html += '</select>'; 
     alert(html); //this alerts <select...></select> 
     //but no option tags because there's nothing to loop through 
     $('lessonsDiv').html(html); 
    }); 
});​ 

一旦你做到了這一點,data將是一個對象,如;

var data = {"lessons": 
[ 
     {"value": "1", "name": "Lesson 1"}, 
     {"value": "2", "name": "Lesson 2"}, 
     {"value": "3", "name": "Three"} 
] 
}; 

所以,你會真正需要使用data.lessons訪問你有陣列(和data.lessons.length檢索它的長度)。

+1

在你的匿名函數中傳遞'data'對象? :/或者我只是被推遲了。 – f0x 2012-03-08 11:43:00

+0

@ f0x:不,我是智障人士;)。 – Matt 2012-03-08 11:43:57

+0

@ f0x如果未定義第二個參數,則不一定需要傳遞數據 – Rafay 2012-03-08 11:45:12

2

你的下面的代碼:

data = $.getJSON('lessons.js') 

不起作用。 AJAX不同步。它是,as its name says,異步。這意味着你不等到答案回來。你指定一個回調函數來處理收到的數據。

例如:

$.getJSON('lessons.js', handleDatas) 
// This function will be executed when the datas come back 
function handleDatas(data) { 
    // use the `data` variable here 
} 

儘管它通常使用的方式:

$.getJSON('lessons.js', function(data) { 
    // use the `data` variable here 
} 

在那裏,我們使用一個匿名函數作爲回調。

欲瞭解更多信息,請看jQuery documentation的例子。

相關問題