douhe6181 2016-07-17 12:42
浏览 26
已采纳

PHP回显按钮仅返回javascript中最后一个回显按钮的值

I have a problem defining var for button value that's dynamic. It works in php, it does not work in my javascript.

Lets say I have 3 php-echoed buttons with values 1, 2 and 3 No matter which I click, it will return value 3, even for buttons that clearly have value 1 or 2. Why? Can't figure it out.

As if javascript only gets the highest or the last value of a button. I'm new to javascript so my knowledge is really small on this.

<script type='text/javascript'>
    function myFunction() {
        var msg_id = document.getElementById('like').value;
        var dataString = 'msg_id=' + msg_id;
            $.ajax({
                type: 'POST',
                url: 'ajaxjs.php',
                data: dataString,
                cache: false,
                success: function(html) {
                alert(html);
                }
            });
    }
</script>

then I have php-echoed form

while($row = mysql_fetch_array($msg_check)) {
    $msgid = $row['id'];
    echo "
    <form method='POST'>
    <input id='like' onclick='myFunction()' type='button' value='$msgid'>
    </form>

external ajaxjs.php

$msgid = $_POST['msg_id'];
echo $msgid;
  • 写回答

1条回答 默认 最新

  • douyan6871 2016-07-17 13:18
    关注

    Try this :

      while($row = mysql_fetch_array($msg_check)) {
            $msgid = $row['id'];
            echo "<form method='POST'>
            <input data-id ="$msgid"  onclick='return myFunction(this)' type='button' value='$msgid'>
            </form>
      }
    

    Ajax :

     <script type='text/javascript'>
             function myFunction(obj) {
               var element_id = $(obj).data('id');
                var msg_id = $(obj).val();
                var dataString = 'msg_id=' + msg_id;
                console.log(dataString ); //see in console
               $.ajax({
                type: 'POST',
                url: 'ajaxjs.php',
                data: dataString,
                cache: false,
                success: function(html) {
                   alert(html);
               }
            });
         }
      </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?