通过javascript调用php函数

时间:2013-06-07 13:01:14

标签: php javascript ajax curl

我想使用webiopi RESTful api,使用ajax显示和更改gpio变量。

我有一个我可以使用的PHP函数,但我不能放弃使用javascript(ajax?)来调用它或者这不是最佳实践。

api的一个例子。

  

设置GPIO功能
    HTTP POST / GPIO /(gpioNumber)/ function /(“in”或“out”或“pwm”)
    返回新设置:“in”或“out”或“pwm”
    例子:
    将GPIO 0设置为输入:HTTP POST / GPIO / 0 / function / in
    将GPIO 1设置为输出:HTTP POST / GPIO / 1 / function / out

     

获取GPIO值
    HTTP GET / GPIO /(gpioNumber)/值
    返回0或1     示例:
    要获得GPIO 0值:HTTP GET / GPIO / 0 / value

和php功能

function WebIOPi($path, $method) {
    $url = 'http://192.168.1.170'.$path;

    // Open Connection
    $ch = curl_init();

    // set the url, user/pass, port
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD, 'webiopi:raspberry');
    curl_setopt($ch, CURLOPT_PORT, 8000);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    // Execute POST
    $result = curl_exec($ch);

    // Close Connection
    curl_close($ch);
    return $result;
}

我假设我也可以以某种方式创建一个数据数组,并创建一个带有按钮来控制引脚的表单。而不是为每个按钮等做..

编辑*

这是我尝试使用的建议,仍然无法与休息服务器通信,我哪里出错了。

    <?php //goes here
    function WebIOPi($path, $method) {
        $url = 'http://192.168.0.17'.$path;

    // Open Connection
    $ch = curl_init();

    // set the url, user/pass, port
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD, 'webiopi:pass');
    curl_setopt($ch, CURLOPT_PORT, 8000);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    // Execute POST
    $result = curl_exec($ch);

    // Close Connection
    curl_close($ch);
    return $result;
}
?>

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>Page Title</title>
    <link rel="stylesheet" href="css/style.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<script>
$.post('http://192.168.0.17/api.php', 
    { 'method':'POST', 'path':'/GPIO/4/function/out' }, 
    function(data) {
        alert(data);
});
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

api.php

中创建一个带有此文件的php文件
$path = $_POST['path'];
$method = $_POST['method'];
... whatever validation you want to do ...
return WebIOPi($path, $method);

然后,在您的网站中加入jQuery(这不是必需的,但会让Ajax更容易):

//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js

然后创建一个这样的JavaScript函数,它会发送一个包含指定数据的请求,然后给你一个响应警告:

$.post('http://whatever/api.php', 
    { 'method':'someMethod', 'path':'somePath' }, 
    function(data) {
        alert(data);
});