如果问题不清楚,我事先表示歉意,但我会尝试。
我目前有这段代码可以从我的家庭自动化 Controller 中提取所有设备的状态。
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']
关于javascript - 将 getJSON 与变量一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34125748/