重复使用由 $.getJSON 填充的 JSON 数据

Reuse of JSON data populated by $.getJSON

我有如下代码:

$.getJSON("jsonlesson.txt", function(json) {
    console.log("success");
    $.each(json.lessonjson, function(key1, val1) {
        $("#lessonid").append("<option value='" + val1.lessonkey + "'>" + val1.lessonval + "</option>");
    });
})
.done(function() {
    console.log("second success");
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
})
.error(function(error) {
    console.log(error);
});

是否可以重新使用由 $.getJSON 填充的 JSON 数据?

我应该能够编写如下代码吗?

lessonArray = jQuery.grep(json.lessonjson, function(product, i) {
            return product.subjectkey == selectedsubject;

如何在另一个函数中为 grep 重新使用 JOSN 数据?

您的代码应如下所示:

$.getJSON('jsonlesson.txt', function (json) {
  console.log('success');
  lessonArray = json.lessonjson;

  //where this lessonArray is global variable.
  $.each(json.lessonjson, function (key1, val1) {
    $('#lessonid').append("<option value='" + val1.lessonkey + "'>" + val1.lessonval + '</option>');
  });
})
  .done(function () {
    console.log('second success');
  })
  .fail(function () {
    console.log('error');
  })
  .always(function () {
    console.log('complete');
  })
  .error(function (error) {
    console.log(error);
  });

然后您可以在整个页面上使用那个 lessonArray 变量。

通过 jQuery.JSON 调用检索数据后,在内部函数中使用之前保存查询的数据。

jQuery("#DOMdata").data(' element, key, value);

然后用这个检索它:

var myData = jQuery("#DOMdata").data(key);

storing json as variable for reuse within another function