为什么我不能立即使用$ .getJSON()的结果?

use*_*572 2 jquery json getjson

我试图让我的$ .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);
});
Run Code Online (Sandbox Code Playgroud)

这是我的lessons.js文件

   {"lessons": 
     [
          {"value": "1", "name": "Lesson 1"},
          {"value": "2", "name": "Lesson 2"},
          {"value": "3", "name": "Three"}
     ]
    }
Run Code Online (Sandbox Code Playgroud)

最终,我要做的是在选择课程时创建一个新的课程选择列表.但就目前而言,我只是想让这个getJSON方法起作用,但事实并非如此.如果有人能看出有什么问题,那就太棒了.是否期待不同类型的数据?

Mat*_*att 7

呼唤getJSON()是异步的; 结果无法立即获得.返回的是监视异步请求状态getJSON()jqXHR对象.

您需要注册一个回调(这是第二个参数的用途),它在响应可用执行.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);
    });
});?
Run Code Online (Sandbox Code Playgroud)

一旦你完成了这个,data就会成为像这样的对象;

var data = {"lessons": 
 [
      {"value": "1", "name": "Lesson 1"},
      {"value": "2", "name": "Lesson 2"},
      {"value": "3", "name": "Three"}
 ]
};
Run Code Online (Sandbox Code Playgroud)

所以你实际上需要用来data.lessons访问你已经拥有的数组(并data.lessons.length检索它的长度).