简体   繁体   English

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

[英]PHP-echoed buttons return only the value of a last echoed button in javascript

I have a problem defining var for button value that's dynamic. 我有一个问题,即为动态按钮值定义var。 It works in php, it does not work in my javascript. 它适用于PHP,它在我的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? 假设我有3个php-echoed按钮,其值为1,2和3无论我点击哪个按钮,它都会返回值3,即使对于明显具有值1或2的按钮也是如此。为什么? Can't figure it out. 无法弄清楚。

As if javascript only gets the highest or the last value of a button. 好像javascript只获取按钮的最高值或最后一个值。 I'm new to javascript so my knowledge is really small on this. 我是javascript的新手,所以我的知识非常小。

<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 然后我有php-echoed表单

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 外部ajaxjs.php

$msgid = $_POST['msg_id'];
echo $msgid;

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 : 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM