语义 UI 搜索表单未获取对象数据

Semantic UI Search form is not fetching object data

我正在从端点中提取国家/地区列表。我认为我正在正确构建对象,但我在搜索表单中没有得到任何结果,但是使用 content[] 的内联声明它工作正常。

API JSON 响应如下所示:

{country: "Albania", code: "AL"}
{country: "Algeria", code: "DZ"}
{country: "Andorra", code: "AD"}
{country: "Angola", code: "AO"}
var content = [];
$.getJSON('/getCountries', function(data){
    $.each(data, function(key, value){
        $.each(value, function(key, value){
            if (key == 'country') {
                content.push({ title: value})
            }
        })
    })
})

$('.ui.search')
  .search({
      source: content
  })

有什么想法吗?

您可以使用纯 javascript:

稍微简化代码
var content = [];

$.getJSON("/getCountries", function (data) {
  parseData(data);
});

function parseData(data) {
  for (var item of data) {
    content.push({ title: item.country });
  }
}

$(".ui.search").search({
  source: content,
});

假设它是一个对象数组,我将其用于数据:

const data = [
  { country: "Albania", code: "AL" },
  { country: "Algeria", code: "DZ" },
  { country: "Andorra", code: "AD" },
  { country: "Angola", code: "AO" },
];

在我看来像是一个异步问题。

$(".ui.search").search()$.getJSON() 返回数据之前被调用。


让我们分解一下正在发生的事情:

/*
$.getJSON() is shorthand for

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
})

which is asynchronous.

See https://api.jquery.com/jQuery.getJSON/
*/

// start the ajax call
$.getJSON(

  // URL from which we're fetching JSON data
  "/getCountries", 

  // the "success" callback function to be executed after a successful request
  function (data) {
    parseData(data);
  }
);

// begins executing immediately after .getJSON()
// without waiting for data to return
$('.ui.search').search({
  // content is still empty at this point, since data hasn't come back yet
  source: content
})


解决方案

我们需要在 异步 .getJSON() 调用 returns 之后调用 .search() 数据。

由于我们已经在使用回调函数,回调函数在我们获取 JSON 数据后执行,让我们在该回调中执行所有 data 操作。

这里我创建了两个较小的函数:一个用于将数据解析为我们希望 content 拥有的形式,另一个用于调用 .search() 以使用该内容初始化搜索表单.

我们现在可以从我们的回调内部调用这两个函数,我们知道我们已经获得了数据。

// set up empty array
var content = [];

// when this is called, use the value of the content array
function populateSearch() {
  $(".ui.search").search({
    source: content
  });
}

// when this is called, push data into the content array
function parseData(data) {
  for (var item of data) {
    content.push({ title: item.country });
  }
}

$.getJSON("/getCountries", function (data) {
  // first parse data into the content array
  parseData(data);

  // then call the function that sets up search
  populateSearch();
});


现代化到 ES6 级别 Javascript

你可以这样写得更简洁:

function populateSearch(data) {
  // use .map() to transform our data array to a new array in one step
  const content = data.map(item => (
    { title: item.country }
  ));

  // init the search form with our new content array
  $(".ui.search").search({
    source: content
  });
}

$.getJSON("/getCountries", function (data) {
  populateSearch(data);
});