duanpi5733 2014-02-28 14:47
浏览 59
已采纳

PHP函数从javascript调用

I am trying to make a simple web GUI for a Raspberry Pi. It is supposed to draw a temperature value on an image using php and JavaScript.

I will use some IPC between PHP and a C++ application I am writing. But right now I just want to read a value from a file and draw it on the image. (The file is a temperature value from a 1wire bus using OWFS)

My problems

  • The JavaScript function ReadTemps() gets called every 5 seconds, but the PHP values only gets updated when the page refreshes.

  • I have NO experience in JavaScript.

The code

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>Still life web application</title>
    <canvas id="myCanvas" width="768" height="576" style="border:0px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>

    <?php
            function get_temp()
            {
                    echo round( floatval( file_get_contents( '/mnt/1wire/uncached/vessel/temperature' ) ), 2 );
            }
    ?>

    <script>
            var bgImg = new Image();
            bgImg.src = 'image.jpg';

            function ReadTemps()
            {
                    var vessel_temp = '<?php get_vessel_temp();  ?>';

                    var c = document.getElementById( "myCanvas" );
                    var ctx = c.getContext( "2d" );

                    ctx.drawImage( bgImg, 0, 0 );

                    ctx.font="20px Georgia";
                    ctx.fillText( vessel_temp + '\u00B0', 330, 430 );

                    setTimeout( ReadTemps, 5000 );
            }
            window.onload = ReadTemps;
    </script>
</head>
<body>
    <a href="javascript:ReadTemps();">Update</a>
</body>
</html>

If I add an alert("hello") in ReadTemps it pops up every 5 seconds.

The solution

<script>
    var bgImg = new Image();
    stillImg.src = 'image.jpg';

    function ReadTemps()
    {
        var vessel_temp = loadXMLDoc( 'get_vessel.php' );

        var c = document.getElementById( "myCanvas" );
        var ctx = c.getContext( "2d" );

        ctx.drawImage( bgImg, 0, 0 );

        ctx.font="20px Georgia";
        ctx.fillText( vessel_temp + '\u00B0', 330, 430 );

        setTimeout( ReadTemps, 5000 );
    }

    function loadXMLDoc( file )
    {
        var xmlhttp;
        if( window.XMLHttpRequest )
            xmlhttp = new XMLHttpRequest();
        else
            xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );

        xmlhttp.open( "GET", file, false );
        xmlhttp.send( null );

        if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
            return xmlhttp.responseText;
        else
            return "error";
    }
    window.onload = ReadTemps;
</script>
  • 写回答

3条回答 默认 最新

  • doukui2011 2014-02-28 15:14
    关注

    The answer is simple, you must use AJAX instead include PHP code inside Javascript, you must to create a php file (get_temp.php) and get it contents with an AJAX call.

    First, create the get_temp.php file:

    <?php // get_temp.php
    print round( floatval( file_get_contents( '/mnt/1wire/uncached/vessel/temperature' ) ), 2 );
    die;
    ?>
    

    Second, adapt your Javascript code to do AJAX calls:

    <script>
    var bgImg = new Image();
    bgImg.src = 'image.jpg';
    
    function ReadTemps() {
        loadXMLDoc('get_temp.php'); 
        setInterval(loadXMLDoc, 5000, 'get_temp.php');
    }
    
    function ShowTemp(temp){
        var c = document.getElementById( "myCanvas" );
        var ctx = c.getContext( "2d" );
    
        ctx.drawImage( bgImg, 0, 0 );
    
        ctx.font="20px Georgia";
        ctx.fillText( temp + '\u00B0', 330, 430 );
    }
    
    function loadXMLDoc(file) {
        var xmlhttp;
        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) {
                    ShowTemp(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET",file,true);
        xmlhttp.send();
    }
    
            window.onload = ReadTemps;
    </script>
    

    As you can see, I added a loadXMLDoc to your code, this function do the AJAX call to any file in your server.

    Of course, you can use jQuery to do the same but it increases the client-side time to load and if you only need to do an AJAX call is completely unnecessary.

    Hope it helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100