2017-05-07 66 views
1

我一直在阅读语义ui远程内容文档的下拉菜单(here),但似乎无法弄清楚如何在我的情况下使用它。加载带有远程数据的语义UI下拉菜单

我有一个函数,查询所需数据的back4app(解析)并将其转换为JSON。如何将返回的数据填充到下拉列表中?我是否必须手动构建它,还是可以直接以某种方式传递JSON?

回答

0

我通过使用ResponseAsync解决了这个问题 - 请参阅下面的代码摘录。这个对我有用。问题是我没有使用解析URL来运行查询 - 对不起,我错过了这个说法。

$('.ui.dropdown.age_group').dropdown({ 
    onChange: function(value, text, $choice){ 
     $('.ui.dropdown.group').dropdown('clear'); 
     GetGroups(); 
    ; 
    }, 
    apiSettings: { 
     responseAsync: function(settings, callback) { 

    var query = new Parse.Query("Teams"); 
     query.ascending("AGE_GROUP"); 
    query.find({ 
    success: function(results) { 
     var jsonArray = []; 

    // Create the JSON array that the dropdown needs 
     for(var i = 0; i < results.length; i++) { 
      jsonArray.push(results[i].toJSON()); 
     } 

    // Create the required json for the dropdown (needs name and value) 
     var myresults = jsonArray.map(function(item) { 
      return { 
       name: item, 
       value: item 
      } 
     }); 

     var response = { 
      success: true, 
      results: myresults 
      }; 
     // This will populate the dropdown 
      callback(response); 
     }, 
     error: function(error) { 

     } 
    }); 
    } 
    } 
}); 
1

在您的下拉初始化,添加apiSettings散列远程数据:

$(selector) 
    .dropdown({ 
     apiSettings: { 
      url: <Your_API_URL>, 
      beforeXHR: (xhr) => { 
       // Set Custom Headers here 
       xhr.setRequestHeader(key, val) 
      }, 
      onResponse: (response) => { 
       // Modify your JSON response into the format SUI wants 
       return response 
      } 
}); 

This是响应格式语义UI预计​​

对于你的使用情况,您可能要打破你的函数分为两部分: 1.获取数据的部分 2.将数据清理成JSON的部分

您必须使用apiSettings哈希来获取da ta为你(只需将你的URL和自定义标题,如身份验证)。这将取代你的功能的第1部分。

当数据返回时,调用SUI的onResponse()方法。在这里调用你的将数据清理成JSON的函数。

您可能需要稍微修改JSON响应以符合SUI的预期。

+0

谢谢。看到我的答案 - 我希望这是正确的方法。如果你想到更好的东西,请告诉我。 – SimpleOne