简体   繁体   中英

How to pass a MySQL data from PHP to Javascript through a function

I'm making a program that shows several descriptions taken from a database (MySQL):

echo "<input type=\"submit\" id=\"Boton" . $i . "\" value=\"Mostrar Descripcion\""
                                            . " onclick=cambiarBoton(" . $i . ", \"" . $row["descripcion"] . "\") />";

echo "<div class=\"entrada-descripcion\" id=\"Descripcion" . $i . "\">  </div>";

where $row["descripcion"] is the access to the description and $i is an identifier because i'm using loops. That code generates a button that i must press to show the description. The javascript function "cambiarBoton" is the one that do that changes:

function cambiarBoton(i, d){

                    if (document.getElementById("Boton"+i).value == "Mostrar Descripcion"){
                        document.getElementById("Boton"+i).value = "Ocultar Descripcion";
                        document.getElementById("Descripcion"+i).innerHTML = d;
                    }else if(document.getElementById("Boton"+i).value == "Ocultar Descripcion"){
                        document.getElementById("Boton"+i).value = "Mostrar Descripcion";
                        document.getElementById("Descripcion"+i).innerHTML = "";
                    }

                }

Ok, but there is a problem in the program and this is that i can't pass the description to the function in javascript and this doesn't works. How can i do this? (I must do this without using AJAX)

我回答我你问的是这个问题:

<?php echo "<script>var data = ".$row["description"].";</script>"; ?>

The problem was in the call of the function "cambiarBoton" in the code PHP, it should have been this:

echo "<input type=\"submit\" id=\"Boton" . $i . "\" value=\"Mostrar Descripcion\""
                                        . " onclick=\"cambiarBoton(" . $i . ", '" . $row["descripcion"] . "')\" />";

And then it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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