简体   繁体   中英

how to pass php variables to javascript function

I have 2 comboboxes and i want to pass the selected value to anoither php by ajax the problem is that how can pass the tow vaules in one function

    <script>
function showUser(str,str2) {
    if (str == "" ||str2 =="" ) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else { 
        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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","cg_comboBox.php?q="+str+"&p="+str2,true);
        xmlhttp.send();
    }
}
</script>

<script>
function fun(v)
{
        document.getElementById("xxx").innerHTML = v;       
}

</script>

html

  <div class="form-group">
        <label for="GroupName" class="col-sm-2 control-label">Movie Name</label>
    <div class="col-md-2">
    <select class="combobox" width="200" style="width: 200px" name="mov" id="mov" onchange="fun(this.value)">
    <option value="">Select Movie </option>
      <?php //code  ?>

    </select>
            <br>
</div>



<label for="GroupName" class="col-sm-2 control-label">Group Name</label>
<div class="col-md-2">
        <?php $x = "<div id=\"xxx\" name=\"xxx\" ><b></b></div>";
        //echo $x;  ?>

    <select class="combobox" width="200" style="width: 200px" onchange="showUser(this.value,x)" id='x'>
        <option value="">Select Cinema Group</option>
      <?php //code ?>

    </select>

i want to add $x value in the second parameter but how?

这应该可以解决您的问题:

onchange="showUser(this.value,'"+<?php echo $x; ?>+"')"

Your problem is most likely that you are naming your script with an HTML or HTM extension. Name your script file with a PHP extension and not an HTML extension. This is a common problem.

Once you do that, the solutions posted by others will work, for example:

<?php $x = 'something!'; ?>
onchange="showUser(this.value,'"+<?php echo $x; ?>+"')"

First assign a value fo $x and then use the value in javascript.

If your .js file is static, and not output by PHP, then have your PHP output a variable dynamic definition, as follows:

var myvar = <?php echo $x; ?>;

And in your HTML page use the variable as follows:

onchange="showUser(this.value, myvar);"

That should do it! :)

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