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 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)