2016-10-27 267 views
1

我目前使用sweetalert2從對話框捕獲用戶的輸入。我想在鏈接隊列對話框中使用下拉列表,但似乎無法找到在下拉列表中動態添加項目的方法。假設我想從JSON格式檢索數據並將其放置在下拉列表中,是否有辦法執行此操作?SweetAlert下拉列表動態添加列表中的項目

function userInput() { 
    swal.setDefaults(
     { 
      showLoaderOnConfirm: true, 
      confirmButtonText: 'Next →', 
      showCancelButton: true, 
      animation: true, 
      progressSteps: ['1', '2', '3'] 
     } 
    ); 

    var steps = [ 
     { 
      text: 'Select an author to analyze the commit', 
      input: 'select', 
      inputOptions: { 
       'SRB': 'Serbia',  // How do I dynamically set value? 
       'UKR': 'Ukraine', 
       'HRV': 'Croatia' 
      } 
     }, 
     { 
      text: 'Select multiple authors to compare their commits', 
      input: 'select', 
      inputOptions: { 
       'SRB': 'Serbia',  // How do I dynamically set value? 
       'UKR': 'Ukraine', 
       'HRV': 'Croatia' 
      } 
     }, 
     { 
      text: 'Select a file directory to analyze all author\'s commit', 
      input: 'select', 
      inputOptions: { 
       'SRB': 'Serbia',  // How do I dynamically set value? 
       'UKR': 'Ukraine', 
       'HRV': 'Croatia' 
      } 
     } 
    ]; 

    swal.queue(steps).then(function(result) { 
     swal.resetDefaults(); 
     swal({ 
      type: 'success', 
      title: 'Success', 
      text: 'Scroll down for statistics!', 
      html: 
       'Your selections: <pre>' + 
       JSON.stringify(result) + 
       '</pre>', 
      confirmButtonText: 'Ok', 
      showCancelButton: false 
     }) 
    }, function() { 
     swal.resetDefaults() 
    }) 
} 

JSON格式數據中檢索:

function getData(repolink) { 
readDataFromGit('https://api.github.com/repos/' + repolink + '/git/trees/master?recursive=1', function(text){ 
     data = JSON.parse(text); 
     $.each(data, function(i, v) { 
      // Retrieve v.login data! 
      data = v.login; 
     }) 
    }); 
} 

function readDataFromGit(link, callback) { 
    var request = new XMLHttpRequest(); 
    request.overrideMimeType("application/json"); 
    request.open('GET', link, true); 
    request.onreadystatechange = function() { 
     if (request.readyState === 4 && request.status == "200") { 
      callback(request.responseText); 
     } 
    }; 
    request.send(null); 
} 

回答

1

作爲SweetAlert2 documentation說,inputOptions參數可以是objectPromise

動態填充選擇項目,你應該使用的承諾,這裏的簡單的例子:

var inputOptionsPromise = new Promise(function (resolve) { 
 
    // get your data and pass it to resolve() 
 
    setTimeout(function() { 
 
    resolve({ 
 
     '#FF0000': 'Red', 
 
     '#00FF00': 'Green', 
 
     '#0000FF': 'Blue' 
 
    }) 
 
    }, 2000) 
 
}) 
 

 
swal({ 
 
    input: 'select', 
 
    inputOptions: inputOptionsPromise 
 
})
<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>

通知書的,SweetAlert2會自動顯示加載程序,直到inputOptions參數的承諾將得到解決或被拒絕。