如何将javascript选择的变量设置为php填充下拉菜单

问题描述 投票:0回答:1

我正在使用javascript中的查询填充php下拉列表。我如何通过js变量进行比较并在php填充的下拉列表中进行设置。我已经尝试过以下代码。

  $.each(jsonData, function( index, value ) {
         var functId=value.functId;

         html +="<tr>  <td><select  id='FunctionName' ><?php foreach($conn- 
        >query( 'select resid as id ,resdesc as value  from FUNCTNAMES')- 
        >fetchAll(PDO::FETCH_OBJ) as $row){ 

//how can i pass functId to compare and set in following option code ???

         $sel = ($row->id== functId)? "selected='selected'":"";

        echo '<option value='.$row->id.' '.$sel.'>' . $row->value . 
        '</option>';}
       ?> </select></td> </tr>";
      })

请建议

jquery json dropdown
1个回答
0
投票

PHP在服务器上运行,而JS在客户端上运行。因此,这两种方式无法以您尝试的方式直接进行通信。

[要解决此问题,请JS用在PHP循环中生成的select元素填充option,然后在将选项添加到DOM后,在JS中设置相关值。像这样的东西:

$.each(jsonData, function(index, value) {
  var functId = value.functId;

  let html = // something...
  html += `<tr><td><select id="FunctionName"><?php foreach($conn->query('select resid as id, resdesc as value from FUNCTNAMES')->fetchAll(PDO::FETCH_OBJ) as $row) {
    echo '<option value="'.$row->id.'">'.$row->value.'</option>';
  } ?></select></td></tr>`;

  $('#yourTable').html(html).find('select').val(functId);
})
© www.soinside.com 2019 - 2024. All rights reserved.