Nest API,单击On按钮,运行更改数据的PHP函数,然后重新加载数据

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

我有一个网站连接我的Nest Thermostat。我试图让HTML向上/向下按钮触发一个功能,该功能可以获取恒温器的目标温度,增加或减少一度,调节恒温器,然后显示恒温器的新设定温度。

我可以使它工作(没有AJAX),但它不漂亮,并将“tempUp / Dn = 1”标签附加到我的网站URL,这会让事情变得混乱。下面显示的是当前设置。如何在这个设置中使用AJAX,这样我就可以浏览index.php并增加/减少温度而无需离开index.php?

我假设我需要这样的东西,但我不知道在哪里适合它:

$.ajax({
   type: "POST",
   url: "something.php",
   success: function(msg){
      alert( 'something' );
   }
 });

index.php文件:

我网站的主要门户网站。有很多东西。只显示部分在哪里带来我的恒温插件

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function(){
        // Load at thermostat 
        $.ajax({
            url: "./thermostat/thermostat.php",
            type: "POST",
            dataType: "text",
            success: function(data){
                $("#thermostat_div").html(data);
            }
        })
 });
 </script>
 <div id=thermostat_div>
     Loading the thermostat...
 </div>

thermostat.php:

显示恒温器的目标温度。还显示用于增加或减少温度的向上和向下按钮。

如果我直接在浏览器中加载此页面,它会起作用。它通过添加“&tempUp = 1”或“&tempDn = 1”url并重新加载页面来工作。但是,当我加载我的主index.php时,按钮会在单击时触发,但温度不会更新。我需要一些东西,所以我可以加载index.php,单击按钮,运行正确的增量/减量函数,然后以某种方式刷新thermometer_div以显示新的设置温度,而不会将垃圾添加到URL。

     <?php 
     // Import the function to adjust the target temp
     include '/var/www/thermostat/functions.php

     // Display the temp the thermostat stat is set to 
     echo "<div class='targetTemp'>".$targetTemp."</div>"; 

    if($_GET['tempDn']){
        $targetTemp = $targetTemp - 1;
        $newTemp = '{"target_temperature_f": ' . $targetTemp . '}';
        changeTemp($newTemp);
    }
    if($_GET['tempUp']){
        $targetTemp = $targetTemp + 1;
        $newTemp = '{"target_temperature_f": ' . $targetTemp . '}';
        changeTemp($newTemp);
    }

    ?>

    <button class="btndn orange" type="button" onClick='location.href="?tempDn=1"'>ᐁ</button>
    <button class="btnup orange" type="button" onClick='location.href="?tempUp=1"'>ᐃ</button>

的functions.php:

<?php
function changeTemp($changeTempTo) {
    include '/var/www/config.php';
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://developer-api.nest.com/devices/thermostats/secretcode",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_CUSTOMREQUEST => "PUT",
        CURLOPT_POSTFIELDS => $changeTempTo,
        CURLOPT_HTTPHEADER => array(
            "authorization: Bearer ".$nestAccessToken,
            "cache-control: no-cache",
            "content-type: application/x-www-form-urlencoded",
            "content-length: ".strlen($changeTempTo)
        ),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
        echo "cURL Error #:" . $err;
    }
}


//Get all the other status off the thermostat
include '/var/www/config.php';
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://developer-api.nest.com/devices/thermostats/secretkey",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_FOLLOWLOCATION => 1,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_POSTFIELDS => "client_id=".$nestClientID."&client_secret=".$nestClientSecret."&grant_type=authorization_code&code=".$nestAuthCode,
    CURLOPT_HTTPHEADER => array(
        "authorization: Bearer ".$nestAccessToken,
        "cache-control: no-cache",
        "content-type: application/x-www-form-urlencoded"
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    $parsed_json = json_decode($response);
    $targetTemp = $parsed_json->{'target_temperature_f'};     
}

?>
php html ajax nest
1个回答
0
投票

嗨,你可以这样做:

在你的php文件中处理这样的事情:

if (isset($_POST["action"])) {
        $action = $_POST["action"];
        switch ($action) {
            case 'update':
                if (isset($_POST["request"])) {
                    $request= $_POST["request"];
                    if ($request == "temperature") {
                       //do your curl here and fill your response then send it
                       echo json_encode($response);
                    }
                }
                break;

        }
    }

action是您想要执行的命令,并且参数可以触发特定的实用程序功能

然后在你的ajax:

function getInfo(action,request) {
   return $.ajax({
        type: "POST",
        url: "getInfo.php",
        data: {action:action, request: request}
    })

}

点击即可将其称为:

$("#myButtonId").on('click',function(){
getInfo('update','temperature').done(function(response){
var data=JSON.parse(response);
if (data != null) {
//fill your forms using your data e.g
$("#yourInput").val(data.temperature);
}
})

})

希望能帮助到你

© www.soinside.com 2019 - 2024. All rights reserved.