简体   繁体   中英

where put variable to this javascript

sorry for stupid question, but my head is not working anymore today and I have to finish this soon.

I have button to call AJAX:

<button onclick="showUser(this.value)" value="' . $row2["xxx"] . '">' . $row2["xxx"] . '</button>`

and function:

<script>
function showUser(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { 
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("maintext").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","maintext.php?q=" +str,true);
  xmlhttp.send();
}
</script>

so far so good. if I want to use this function with variable from php, how? Or I could write new function with the same purpose, but where to put variable? I tried:

if (isset($_GET['info'])) {
  echo '<script> function showUser(' . $_GET["info"] . ') </script>';
} 

...but it doesn`t work.

Thanks for help

You are re-defining the function. You just have to call it after (!) you defined it.

Replace

if (isset($_GET['info'])) {
  echo '<script> function showUser(' . $_GET["info"] . ') </script>';
} 

with

if (isset($_GET['info'])) {
  echo '<script> showUser("' . $_GET["info"] . '") </script>';
} 

Additionally you have to insert quotes ( " " ) or Javascript won't take the input as a string.

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