添加从后端生成的输入选项

时间:2016-10-23 15:20:18

标签: javascript php jquery sweetalert

我在下面包含此代码时遇到了一些问题。这是名为Sweet Alert 2的库的功能。我想从php

加载“inputOptions”

我现在的代码:

    function pick(){
    swal({
  title: 'Choose country',
  input: 'select',
  inputOptions: {
    'SRB': 'Serbia',
    'UKR': 'Ukraine',
    'HRV': 'Croatia'
  },
  inputClass: 'form-control select',
  confirmButtonColor: '#78339b',
  inputPlaceholder: 'choose country',
  showCancelButton: true,
}).then(function(result) {
  swal({
    type: 'success',
    html: 'You selected: ' + result
  })
});
}

我想参与这样的输入选项:

<?php
$ct = mysql_query("SELECT * FROM db WHERE typ = 1",$link);                                             
while($row = mysql_fetch_array($ct)){
echo $row['id'] : $row['country'];
}
?>

我知道这不行,但你知道我的意思。有人真的可以帮助我吗?我真的很感激有关如何做到这一点的任何提示

1 个答案:

答案 0 :(得分:0)

您可以通过jQuery中的$.post向您的php文件发送请求来获取您的选项:

function pick(){
$.post("option.php", {options: options}, function(result){
        if(result){
swal({
  title: 'Choose country',
  input: 'select',
  inputOptions: result,
  .
  .
  .

 });
}
....

对于php文件应该是这样的:

// you can get the data you need by senting option to your page $_POST['options']    
$ct = mysql_query("SELECT * FROM db WHERE typ = 1",$link);           
    while($row = mysql_fetch_array($ct)){
        $data[$row['id']] = $row['country'];
    }
    echo json_encode($data);

修改

如果您不想动态获取选项,可以在制作页面时将其添加到代码中:

<?php 
$ct = mysql_query("SELECT * FROM db WHERE typ = 1",$link);           
    while($row = mysql_fetch_array($ct)){
        $data[$row['id']] = $row['country'];
    }
?>
<scirpt>
function pick(){
    swal({
  title: 'Choose country',
  input: 'select',
  inputOptions: <?php echo json_encode($data); ?>,
  inputClass: 'form-control select',
</scirpt>