如何调用php函数“oninput”就像调用javascript函数一样?

问题描述 投票:-1回答:1

这段代码与php一起使用“提交”按钮,但我希​​望它在运行时。所以我想使用“oninput”但它是javascript函数。什么是可能的替代?

<?php
    $new_name = "";
    function my_php_function()
    {   
        echo "Hello {$_POST['user_name']}";
        $new_name = $_POST['user_name'];
    }
    ?>

    <html>

    <form action="" method="post">
        Name:  <input type="text" name="user_name" oninput="my_php_function()" /><br />
        new_name:  <input type="text" name="new_name" value="<?php echo $new_name; ?>"/>  
    </form>

    </html>
javascript php forms
1个回答
0
投票

使用绑定到oninput事件的ajax函数来调用php函数的示例。

<?php
    $new_name='';

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        function my_php_function( $name ){
            $name = !empty( $_POST['user_name'] ) ? $_POST['user_name'] : $name;
            return $name;
        }
        exit( my_php_function( &$new_name ) );
    }
?>
<html>
    <head>
        <title></title>
        <script>
            /* a re-usable ajax function */
            function ajax( url, params, callback ){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( this.readyState==4 && this.status==200 ) callback.call( this, xhr.response );
                };

                var payload=[];
                for( var n in params )payload.push( n+'='+params[n] );
                payload=payload.join('&');

                xhr.open( 'POST', url, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( payload );
            }

            /* event handler to send ajax request */
            function call_my_php_function( event ){
                ajax.call( this, location.href, { user_name:event.target.value }, function(r){
                    document.querySelector('input[name="new_name"]').value=r;
                });
            }
        </script>
    </head>
    <form method='post'>
        Name:  <input type='text' name='user_name' oninput='call_my_php_function( event )' /><br />
        new_name:  <input type='text' name='new_name' value='<?php echo $new_name; ?>'/>  
    </form>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.