我一直在爲此工作一整天,但認爲我對學習AJAX時可用的各種方法感到困惑。我想讓我的網站顯示Python腳本的結果。我可以做到這一點。通過AJAX將PHP變量傳遞給另一個DIV中的PHP變量
問題是腳本的結果隨機更改(這是我車庫門的狀態),如果車庫門的狀態發生變化,我的站點很笨重。通常用戶必須不斷重新加載頁面才能獲得當前狀態。我試圖讓DIV顯示狀態每5秒更新一次,從而顯示新狀態。
Python腳本需要大約4秒鐘才能運行,所以我想繼續將它作爲函數調用,並將其作爲DIV傳遞到我想要顯示結果的網站上。
如果可能的話,一個PHP文件(index.php)。這是我期望做的骨架。我的get_status函數可以工作,但是我對其餘的部分感到不知所措。
謝謝。
編輯:代碼更新與評論發現小調整。
<html>
<body>
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
echo $status;
}
?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
var java_status = <?php echo json_encode(get_status) ?>;
// I have no idea how to pass a variable from PHP thru javascript to PHP on the
// same page. Trying to pass on results of get_status function every 5 seconds.
setInterval(function(){
$.ajax({
url: "index.php"
type: "POST"
dataType: "json"
data: ({status: java_status}),
success: function(data){
$("#status_div").html(data);
}
})
}, 5000);
</script>
<div id="status_div">
<?php
$new_status = json_decode(data);
?>
// I have no idea how to get that status variable here.
The Garage Door Status is: <?php
echo $new_status;
?>
</div>
</body>
</html>
[你看了在瀏覽器的開發者工具的AJAX請求/響應?你有沒有在項目中包含jQuery庫?是否有任何錯誤報告?你在網絡服務器上運行它嗎?](http://jayblanchard.net/basics_of_jquery_ajax.html) –
你根本不需要'#status_div'中的任何代碼。你應該在你的成功函數中解析'data'並將必要的部分放在'#status_div'中 –
你的Python代碼是否返回JSON? –