如何使用 AJAX 从网络服务器请求变量? [英] How do I request a variable from the webserver using AJAX?
问题描述
我的 JavaScript 中有一个循环,它不断检查变量 EventCounter
,如果 eventcounter 为零,则它继续执行一个操作,然后将其递增 ++,然后它什么也不做,直到该变量发生变化,这里是代码:
I have a loop in my JavaScript that is constantly checking the variable EventCounter
, if eventcounter is zero then it proceeds to do an action then increment it ++, And then it proceeds to do nothing, until that variable changes, here is the code:
EventCounter = {{eg.globals.EventCounter}};
for(var i = 0; i < n; ++i) {
r = rects[i];
ctx.strokeRect((r.x*sc)|0,(r.y*sc)|0,(r.width*sc)|0,(r.height*sc)|0);
window.rects = rects[i];
//console.log(EventCounter);
if (EventCounter === 0) {
console.log("event counter is" + EventCounter)
//setTimeout( function () {document.getElementById("sb").click()}, 5000)
EventCounter++
console.log("event counter is now " + EventCounter);
}
}
}
现在 EventCounter 全局变量从网络服务器(它的一个 python 网络服务器和它的一个 python 变量)获取它的值.
Now the EventCounter global variable gets its value from the webserver (its a python webserver and its a python variable).
但我的问题是如何检测网络服务器上的变量已更改?一个ajax请求对吗?我将如何请求变量值来检测它是否已更改,以便循环可以再次运行?(**服务器与PHP不兼容)
But my question is how do I detect that the variable has changed on the webserver? an ajax request right? how would I go about requesting the variable value to detect if it has changed so that loop can run again? (**the server is incompatible with PHP)
推荐答案
这是一个 jQuery 实现,它每 1000 毫秒轮询一次服务器脚本并显示结果.您的典型响应时间 + 浏览器处理时间应明显少于您的轮询间隔,否则您的请求可能会备份.
Here's a jQuery implementation that polls the server script every 1000ms and displays the result. Your typical response time + browser processing time should be significantly less than your polling interval or your requests might back-up.
Javascript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>eventCounter</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var interval = setInterval(function() {
// this is where your ajax call is made.
$.ajax('geteventcounter.php', {
cache: false,
dataType:'json',
success: function(data) {
// do your browser-side processing here.
$('#eventCounter').text(data.eventcounter);
}
});
}, 1000);
</script>
</head>
<body>
<p>eventCounter is <span id=eventCounter></span></p>
</body>
</html>
服务器端 PHP:对于此示例,使用会话变量,它会在每次请求时递增并返回 JSON 字符串.
Server side PHP: For this example, uses a session variable which it increments on every request and returns a JSON string.
<?php
session_start();
// initialise counter, or increment it.
if (isset($_SESSION['eventcounter'])) {
$_SESSION['eventcounter']++;
} else {
$_SESSION['eventcounter'] = 0;
}
// set output mime type
header("ContentType: application/json");
// copy session variable to a new array, convert to JSON and send.
echo json_encode(['eventcounter' => $_SESSION['eventcounter']]);
?>
这篇关于如何使用 AJAX 从网络服务器请求变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!