简体   繁体   English

使用php中的变量作为javascript的警报

[英]use variable from php as an alert for javascript

how can i use the variable from my php-sql to become the message for my javascript alert? 我如何使用我的php-sql中的变量成为JavaScript警报的消息?

heres my code 这是我的代码

<?php

    $select = "SELECT * FROM post";
    $result = mysql_query($select) or die("couldn't select table");


    while ($rows = mysql_fetch_array($result))
    {
        echo"<input type='button' class=term onclick='return terms()' value=Terms >";

        echo"<input type='hidden' value='$rows[terms]' id='term' name='term'>";
    }
?>  

<script language="JavaScript">
    function terms() 
    {
        var readers = document.getElementById("term"); 
        alert(readers.value);
    }
</script>

It works, the alert message displays. 它有效,显示警告消息。 But I got the problem on displaying the right message for specific fetch of row. 但我上显示正确的信息特定的抓取行的问题。 All got the same message (message from the first row). 所有人都收到相同的消息(第一行的消息)。

I tried to use getElementByName but the alert doesn't pop-up, so i dont have to try making the input name="term[]" --------(into its array form) 我尝试使用getElementByName,但不会弹出警报,因此我不必尝试使输入名称=“ term []” --------(转换为数组形式)

Help please! 请帮助!

将while循环内的第二个echo语句更改为:

echo"<input type='hidden' value='". $rows['terms'] ."' id='term' name='term'>";

I think it will be find if you change this line of script 我认为,如果您更改此脚本行将会找到

 echo"<input type='button' class=term onclick='terms()' value=Terms >";

onclick='terms()' here, instead of onclick='return terms()' onclick ='terms()',而不是onclick ='return terms()'

EDIT: 编辑:

<?php   echo"<input type='button' class=term onclick='terms(this)' data-result ='". $rows['terms'] ."' value=Terms >"; ?>
      /* Remove the hidden field */
<script language="JavaScript">
    function terms(e) 
    {
        var readers = e.getAttribute('data-result'); 
        alert(readers);
    }
</script>

I usually do the following: 我通常会执行以下操作:

<?php
  function alert($text){
    echo '<script type="text/javascript">alert("'.$text.'")</script>';
  }

  alert("test");
?>

Hope that helps. 希望能有所帮助。

You are overwriting the value or "term" in your HTML code after each iteration of While-loop. 在每次While循环迭代之后,您都将覆盖HTML代码中的值或“项”。 This way it will only get the last value 这样只会得到最后一个值

All of your input elements have the same id . 您所有的input元素都具有相同的id If you want to distinguish them, give them different identifiers. 如果要区分它们,请给它们提供不同的标识符。 And pass the identifier to the terms function. 并将标识符传递给terms函数。

You must give different id for each element. 您必须为每个元素提供不同的ID。 I think simple way to do that is by using auto increment for the id. 我认为,执行此操作的简单方法是对ID使用自动递增。

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

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