私も始めた当初は、そのようなコードをどのように構築するかという概念に苦労しました。特定の変数に固有のものではありませんが、jQuery/PHP を使用して AJAX を介して変数を更新する方法の簡単な例を次に示します。
プロローグ: これを頻繁に行う場合は、通常の JavaScript を単独で使用するよりも、jQueryを学習する必要があります。jQuery の学習方法については、優れた無料のリソースがたくさんあります。また、オンラインの無料のチュートリアルに満足できない場合は、これは優れた本です。例を jQuery で書きます。
設計: では、仕組みは次のとおりです。
X秒ごとに特定の機能を実行するようにjavascriptでタイマーを設定します(毎秒実行したくありません)。
この関数は、サーバー上の .PHP ファイルに対して (jQuery を使用して) AJAX 呼び出しを行い、必要なデータを送信して、.PHP コードが何を送り返すかを認識できるようにします。
.PHP コードは、(MySQL などで) 必要なデータを取得し、それを JSON 形式にエンコードして終了します。
AJAX 呼び出しの promise が起動され、PHP から送信されたデータが受信されます。好きなように処理してください。
手順 2 から繰り返します。
コードの動作についてご不明な点がございましたら、お問い合わせください。
AJAX.PHP
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$return_obj = array();
$request_obj = NULL;
// our AJAX call used "POST" as it's 'type', so we look in that
// variable.
if ( array_key_exists("func",$_POST) ) {
if ( $_POST['func'] === "get_update" ) {
if ( array_key_exists("which_var",$_POST) ) {
$which_var = $_POST['which_var'];
$which_var = $mysqli->real_escape_string($which_var); // should use prepared statements
// we sent 'num_people_logged_in' as our value here, so we'll be looking for a column/field
// with that value. this assumes that some other code, somewhere else,
// is regularly updating the table. it also assumes that there will only
// be a single row returned, which will hold the value.
$query = "SELECT '$which_var' FROM site_stats ";
if ( $result = $mysqli->query($query) ) {
if ( $row = $result->fetch_assoc() ) {
$request_obj[$which_var] = $row[$which_var];
}
}
}
}
}
$return_obj['request'] = $request_obj;
echo json_encode($return_obj);
die();
?>
マイコード.JS
// this actually sends the AJAX request to the server.
function getUpdate() {
var jqXHR = $.ajax({
url : "ajax.php",
data : {
'func' : 'get_update',
'which_var' : 'num_people_logged_in'
},
dataType : 'json',
type : 'POST',
timeout : 10000
});
// attach 'promises' to the jqXHR object, which represents
// the AJAX call itself. 'promises' are, in this context,
// just events.
jqXHR.done(function(data,textStatus,jqXHR) {
// this executes if the AJAX call succeeded.
// the variable 'data' holds what the server
// sent us.
if ( ( data ) && ( data.request ) ) {
receiveUpdate(data.request);
}
});
jqXHR.fail(function(jqXHR,textStatus,errorThrown) {
// this executes if it failed
console.log("Fail: " + textStatus + " (" + errorThrown + ")");
});
jqXHR.always(function(a,textStatus,c){
// this executes either way, after .done or .fail
});
}
// this is called from jqXHR.done, on success
function receiveUpdate(request_obj) {
if ( request_obj.num_people_logged_in ) {
updateDOM(request_obj.num_people_logged_in);
}
}
function updateDOM(num_people_logged_in) {
if ( num_people_logged_in ) {
$("#mydiv > p.update").html("The updated value is: " + num_people_logged_in);
}
}
var timeoutID = null;
// setup our timer, to periodically make an
// AJAX call
function init() {
timeOutID = setInterval(function(){
getUpdate();
},5000);
}
// stop the timer
function cleanup() {
clearTimeout(timeoutID);
}
INDEX.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>AJAX practice</title>
<!-- <link href="mycss.css" rel='stylesheet'> if needed -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="mycode.js"></script>
<script>
$(document).ready(function() {
init();
$("#cleanup").on("click",function(){
cleanup();
});
}); // end ready
</script>
</head>
<body>
<div id='mydiv'>
<p>
How many people are online?
</p>
<p class='update'>
</p>
</div>
<button id='cleanup'>Stop updating!</button>
</div>
</body>
</html>