在我的 html 中,我想调用一个 php 脚本(它调用一个 python 脚本并检查我的 nas 是在线还是离线 - 这工作正常)并返回我"在线"或"离线"。根据结果,我的在线/离线指示器的类("标签标签成功"到"标签标签危险")和文本("在线"到"离线")应该会发生变化。我该如何实现这一点?
.HTML
<span class="label label-success">Online</span>
.PHP
<?php
$result = popen("pingnas.py", "r");
return $result;
?>
您可以对 php 脚本进行 AJAX 调用,而 php 脚本又调用 python 脚本来检查用户是在线还是离线。
像这样的东西。
-In your Javascript, make an AJAX call to PHP script.
-PHP in turn executes python to see if the user is online or offline.
-Send the JSON response. May be something like {"status":"online"}
-Based on the JSON response, change the HTML of the span element.
将 ID 添加到要操作的范围
<span class="label label-success" id="indicator">Online</span>
将结果变量返回给javascript,然后使用javascript操作文本/类名。假设 python 脚本返回 1 表示成功,返回 0 表示失败
<?php
$result = popen("pingnas.py", "r");
?>
<html>
<head>
<script type='text/javascript'>
var setStatus = function(status) {
var ind = document.getElementById('indicator');
if (status === 1) {
ind.innerHTML='Online';
ind.className='label label-success';
return;
}
ind.innerHTML='Offline';
ind.className='label label-fail';
}
window.onload = function() {
setStatus(<?php echo $result ?>);
};
</script>
...rest of the HTML