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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?