douya8978 2017-03-13 07:21
浏览 42
已采纳

在JavaScript中插入PHP函数[重复]

This question already has an answer here:

I have a multiple select input:

<select name="empleados[ ]" id="empleados" class="form-control inputstl"  onChange="getSelectedOptions(this)" multiple>
<option value=""></option>

I want to show on a div the selected items:

<div id="lista"></div>

I am getting the selected items with function getSelectedOptions(this):

<script>

function getSelectedOptions(sel) {
  var opts = [],
    opt;
    var div = document.getElementById('lista');
     div.innerHTML = "";
  var len = len = sel.options.length;
  for (var i = 0; i < len; i++) {

    opt = sel.options[i];

    if (opt.selected) {
      opts.push(opt);


      div.innerHTML =  div.innerHTML +  opt.value + " - ";
    }
  }

  return opts;
}
</script>

It is working fine. But I need to translate the returned values.

For example, the returned array is : 567 - 858 - 363

I have an external PHP function that receive the id number and returns a name.

The function is: get_nombre($id).

How can I insert the PHP function inside JS?

I have tried as follows, but throws an error:

div.innerHTML =  div.innerHTML + " <?php echo get_nombre(?> opt.value<?php )?>" + " - ";
</div>
  • 写回答

1条回答 默认 最新

  • duangengruan2144 2017-03-13 07:31
    关注

    I'm pretty sure, you dont need PHP at this point, because options should already have a text, which could be used.

    function getSelectedOptions(sel) {
      var opts = [],
        opt;
        var div = document.getElementById('lista');
         div.innerHTML = "";
      var len = len = sel.options.length;
      for (var i = 0; i < len; i++) {
    
        opt = sel.options[i];
    
        if (opt.selected) {
          opts.push(opt);
    
    
          div.innerHTML =  div.innerHTML +  opt.text + " - ";
        }
      }
    
      return opts;
    }
    

    If the inner text of the option don't contain the text you want, you could also use data attributes and add the desired text to them.

    <option value="someid" data-text="text">other text</option>
    

    and with javascript

    var text = opt.dataset.text;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作