【问题标题】:TypeError: a is undefined in JavaScriptTypeError:a 在 JavaScript 中未定义
【发布时间】:2016-01-20 08:44:29
【问题描述】:

我创建了一个 JSON 读取函数,但出现错误:

类型错误:a 未定义

这是我的代码:

$(function() {
    var json = $.getJSON("http://localhost/stratagic-json/project_json.php", function() {
        console.log("success");
    });
    var mhtml = '';
    $.each(json.slider, function(key, val) {
        mhtml += '<li><div class="proj-details-wrap"> <img src="images/' + val.image + '" />';
        mhtml += '<div class="proj-badge">' + val.status + '</div>';
        mhtml += '<div class="proj-name">' + val.name + ' <span>' + val.location + '</span> </div>';
        mhtml += '</div>';
        mhtml += ' <div class="container proj-desc">' + val.description + '</div>';
        mhtml += '</li>';
    });
    var $ul = $('<ul class="slides">').append($(mhtml)); // append DOM only one time.
    $('.slider').append($ul);
})

【问题讨论】:

标签: javascript jquery typeerror


【解决方案1】:

问题在于$.getJSON 是一种异步方法,而您正在同步处理它。 json.sliderundefined 因为 $.getJSON 实际上返回一个承诺,而不是数据。需要通过回调或承诺访问数据。这应该有效:

$(function() {
    $.getJSON("http://localhost/stratagic-json/project_json.php", function(json) {
      var mhtml = '';
      $.each(json.slider, function(key, val) {
          mhtml += '<li><div class="proj-details-wrap"> <img src="images/' + val.image + '" />';
          mhtml += '<div class="proj-badge">' + val.status + '</div>';
          mhtml += '<div class="proj-name">' + val.name + ' <span>' + val.location + '</span> </div>';
          mhtml += '</div>';
          mhtml += ' <div class="container proj-desc">' + val.description + '</div>';
          mhtml += '</li>';
      });
      var $ul = $('<ul class="slides">').append($(mhtml)); // append DOM only one time.
      $('.slider').append($ul);
    });
})

你也可以这样做:

$(function() {
    var jqXhr = $.getJSON("http://localhost/stratagic-json/project_json.php");
    jqXhr.done( function (data) {
      // Do something
    });
})

【讨论】:

    猜你喜欢
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    相关资源
    最近更新 更多