2017-05-07 62 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