通过AJAX发送一个PHP变量值


Send a PHP variable value through AJAX

我目前正在使用AJAX来获取服务器上在线玩家的数量。我使用以下代码调用主页上的ajax函数:

<script>
$(document).ready(function() {
    setInterval(function() {
        $.get("avatarquery.php", function(players) {
            $("#playersPLZ").text(players);
        });
    }, 3000);
});
</script>

在avatarquery.php页面上,我有以下php代码:

<?php
require_once 'checkinfo.php';
echo getPlayersTotal();
?>

最后,我在checkinfo.php页面上使用以下代码来ping服务器,并将数据发送回以前的页面:

<?php
function getPlayersTotal() {
$version = 0;
//ini_set("display_errors", 1);
//ini_set("track_errors", 1);
//ini_set("html_errors", 1);
//error_reporting(E_ALL);

$SERVER_IP = "37.187.139.123"; 
$SERVER_PORT = "26618"; 
$QUERY_PORT = "26618";
$HEADS = "3D"; 
$show_max = "unlimited"; 
$SHOW_FAVICON = "on"; 
$TITLE = "My fancy Serverpage";
$TITLE_BLOCK_ONE = "General Information";
$TITLE_BLOCK_TWO = "Players";
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$ping = json_decode(file_get_contents('http://api.minetools.eu/ping/' . $SERVER_IP . '/' . $SERVER_PORT . ''), true);
$query = json_decode(file_get_contents('http://api.minetools.eu/query/' . $SERVER_IP . '/' . $QUERY_PORT . ''), true);

if(empty($ping['error'])) { 
$version = $ping['version']['name'];
$online = $ping['players']['online'];
$max = $ping['players']['max'];
$motd = $ping['description'];
$favicon = $ping['favicon'];
}
if(empty($query['error'])) {
$playerlist = $query['Playerlist'];
}
return $version;
}
echo getPlayersTotal();
?>

目前,$SERVER_IP和$SERVER_PORT变量直接在checkinfo.php代码中定义。但是,我想从主页面发送这些变量的值。我该怎么做?

将它们作为参数添加到函数中,例如

function getPlayersTotal($ip, $port) { ... }
echo getPlayersTotal($_REQUEST['ipcheck'], ...);

或者只是移动主文件中的变量定义:

$SERVER_IP = $_REQUEST['ipcheck']; 
$SERVER_PORT = $_REQUEST['portcheck']; 
require_once 'checkinfo.php';