如何在下拉菜单中调用PHP函数?

时间:2016-06-09 16:26:53

标签: php html call

我想通过onchange事件在下拉菜单中调用php函数。我想选择其中一个选项,从数据库中读取相应的值,并在另一个下拉菜单中列出。

<?php

function read() {

mysql_connect("localhost", "username", "password");

mysql_select_db("database_name");

$sql = mysql_query("SELECT name FROM table");

if (mysql_num_rows($sql)) {
    $select = '<select name="select">';
    while ($rs = mysql_fetch_array($sql)) {
        $select.='<option value="' . '">' . $rs['name'] . '</option>';
    }
}
$select.='</select>';
echo $select;
} 
?>

    <!--html code -->

    <select onchange="document.write('<?php read(); ?>');">
    <option value="0">a</option>
    <option value="1">b</option>
    <option value="2">c</option>
    </select>

此代码输出: enter image description here

我想要的输出: enter image description here

如何获得我想要的输出?感谢

2 个答案:

答案 0 :(得分:1)

只是解释:

在页面在用户浏览器(服务器端)中呈现之前,执行PHP代码。

另一方面,Javascript在客户端执行。这意味着php已经完成了执行。

如果您想调用php函数,则必须向服务器发出另一个请求

要做到这一点&#34;在飞行中#34;你必须使用AJAX,正如@Jon在评论中所说的那样。

以下是使用jQuery的示例(只是一个javascript库,以简化我们的任务):

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javasript">

    //Listen to select 'onchange' event
    $('select#your_select_id').change(function(){

        //Read selected value
        var inputValue = $(this).val();

        //Make an ajax call
        $.post('ajaxscript.php', { value: inputValue }, function(data){

            //The return of 'read' function will be accessible trough 'data'

            //You may create DOM elements here
            alert('Finnished');

        });

    });

</script>

这是我们的 ajaxscript.php 内容:

<?php
//Declare (or include) our function here
//function read(){ ... }

$value = $_POST['value']; //Selected option
//...

echo read();

答案 1 :(得分:1)

您好您也可以在此使用javascript form submit并致电php function

<?php
function read() {
mysql_connect("localhost", "username", "password");
mysql_select_db("database_name");
 $sql = mysql_query("SELECT name FROM table");
if (mysql_num_rows($sql)) {
$select = '<select name="select">';
while ($rs = mysql_fetch_array($sql)) {
$select.='<option value="' . '">' . $rs['name'] . '</option>';
 }
}
 $select.='</select>';
echo $select;
 } 
 if (isset($_POST['value'])) {
  read($_POST['value']);
}
    ?>
  <form method="POST">
 <select name="value" onchange="this.form.submit()">
 <option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
</select>
 </form>