2015-12-07 63 views
2

如果问题不明确,我很抱歉,但我会尝试。使用getJSON与变量

我目前有这样的代码,可以从我的家庭自动化控制器中获取所有设备的状态。

function pull_light_status (lights_array) { 
     $.getJSON("resources/php/getjson.php", function(json) { 
      var vera_obj = json; 
      $.each(lights_array,function(myindex, myvalue){ 
      var id_del_object = myvalue; 
      var id_status = vera_obj.devices[id_del_object].states[0].value; 
     }) 
     })  
    } 

由于目标i得到了越来越真的很难,我与该对象工作,所以我在用另一条路线正在考虑的结构。

我可以用这个PHP叫change_state.php

<?php 
$url = 'http://ip:port/data_request?id=variableget&DeviceNum' . $_POST['device_id'] . "&serviceId=urn:upnp-org:serviceId:SwitchPower1&Variable=Status"; 
$jsondata_send = file_get_contents($url); 
//echo $jsondata_send; 
?> 

我的问题是得到一个特定设备的状态:
是否有可能取代JS的东西,让我请求我指定的设备变量的json响应?

这样的事情?

function pull_light_status (lights_array) { 
     $.each(lights_array,function(myindex, myvalue){ 
      $.getJSON("resources/php/change_state.php",{ device_id: + myvalue}) 
         .done(function(json) { 
       var vera_obj = json; 
       console.log (vera_obj); 
      }) 
     }) 
    } 

我期望的回报是0或1,这样我可以与设备的状态发挥。

+0

*的东西像*应工作,虽然你的PHP正在寻找一个'$ _POST'变量;根据定义,任何通过'getJSON()'传递的'data'参数都将在'$ _GET'(和'$ _REQUEST')中。 –

+0

in change_state.php如果您使用GET请求,您应该阅读'$ _GET ['device_id]'变量。但是,如果你更新服务器中的一些数据,你应该使用POST而不是GET – dann

+0

感谢您的提示,我试过但都没有工作,我没有得到任何东西在控制台上。在网络上我看到这个,当我检查10.0.0.119/resources/php/change_state.php?device_id=12但在控制台上,我没有得到任何回报 – jss

回答

0

尝试使用$.post,因为您期望php侧的POST有效载荷。

function pull_light_status (lights_array) { 
    $.each(lights_array,function(myindex, myvalue){ 
     $.post("resources/php/change_state.php", { device_id: myvalue }) 
      .done(function(data) { 
       var vera_obj = json; 
       console.log (vera_obj); 
     }); 
    }) 
} 

而在php方面,你需要确保你是回送一个json编码字符串。
因此,var_dump($jsondata_send);将是正确的,如果它是正确的,与标题一起打印出来。

<?php 
    $url = 'http://ip:port/data_request?id=variableget&DeviceNum' . $_POST['device_id'] . "&serviceId=urn:upnp-org:serviceId:SwitchPower1&Variable=Status"; 
    $jsondata_send = file_get_contents($url); 

    header('Content-Type: application/json'); 
    print $jsondata_send; 
?> 

如果你想使用getJSON相反,在php文件,更改$_POST['device_id']$_GET['device_id']

+0

谢谢我尝试了你的建议,我只需要做一些线上的细微变化var vera_obj = json;我改为var vera_obj = data;它似乎在工作。万分感谢!!!!!! – jss