douchuifk90315 2018-03-03 07:36
浏览 47

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

This code was working with php for "submit" button but I want it on runtime. So I want to use "oninput" but it is javascript function. What is possible alternate?

<?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>
  • 写回答

1条回答 默认 最新

  • dongyuan7110 2018-03-03 08:21
    关注

    An example of using an ajax function bound to the oninput event to call your php function.

    <?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>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法