如果问题不清楚,我事先道歉,但我会尽力的。
我现在有这个代码,可以从我的家庭自动化控制器中提取所有设备的状态。
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;
})
})
}
由于对象的结构,我很难处理该对象,所以我正在考虑使用另一种方法。
我可以通过使用这个名为change_state.php 的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,这样我就可以处理设备的状态。
请尝试使用$.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']