嗨我试图使用多种ajax函数,我不确定是否可行。
当您输入用户名
时,系统会调用我的第一个onkeyup="UsernameTaken(this.value);"
另一个用身体调用
onload="BattlePlayers();"
功能就像这样
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function UsernameTaken(name){
if (name == "") {
document.getElementById("UsernameTaken").innerHTML = "";
return;
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("UsernameTaken").innerHTML = this.responseText;
}
};
xhttp.open("GET", "CheckUsername.php?q="+name, true);
xhttp.send();
}
function BattlePlayers(){
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("BattleTable").innerHTML = this.responseText;
}
};
xhttp.open("GET", "GetPlayers.php", true);
xhttp.send();
}
然后,似乎总是返回空白的战斗机的php就是这个
<?php
$link = mysqli_connect("","","","");
if (isset($_SESSION['username'])) {
$x = 0;
$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 5; ";
$result = mysqli_query($link,$sql);
$toecho ="";
while($row = mysqli_fetch_assoc($result)){
if($row['username'] !== $_SESSION['username']){//add so it dosent put duplicates
$toecho .="<tr>";
$toecho .="<th>".$row['username']." </th>";
$toecho .="<th>Level: ".$row['Level']." </th>";
$toecho .="<th>Player Stats:".$row['Attack']."/".$row['Defence']." </th>";
$toecho .="<th>Win Chance: ";
$toecho .= CalculateWinChance($link,$row['Defence']);
$toecho .="<input type='hidden' name='hidden1' value='".$row['Defence']."' />";
$toecho .="<input type='hidden' name='hidden2' value='".$row['username']."' />";
$toecho .="<th><input type ='submit' name = 'Attack_Btn' value ='Attack'></th>";
$toecho .="</tr>";
}
}
echo $toecho;
}
?>
它似乎根本没有到达战斗人员,我已经尝试回应来自玩家的警报而没有任何事情发生。我已经确认通过在不同阶段发出警报来调用javascript。只是当它到达getplayers时,它似乎停止了。我在这做错了什么?
答案 0 :(得分:1)
如果您从逻辑上考虑ajax请求的作用,那么您将意识到,如果通过ajax调用的页面需要访问会话变量,那么,因为它实际上是与发起请求的页面分开的独特请求,您需要在该脚本中加入session_start()
。
如果您有一个标准的PHP页面,如:
<?php
session_start();
include 'functions.php';
include 'classes.php';
include 'GetPlayers.php';
?>
<html>
<head>
<title></title>
</head>
<body>
<!-- stuff -->
</body>
</html>
在上面的示例页面中,您的脚本GetPlayers.php
将有权访问该会话。
<?php
session_start();
include 'functions.php';
include 'classes.php';
?>
<html>
<head>
<title></title>
</head>
<body>
<script>
xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.status==200 && xhr.readyState==4 ){
alert( xhr.response );
}
};
xhr.open( 'GET','GetPlayers.php',true );
xhr.send();
</script>
</body>
</html>
此处,如果session_start()
顶部没有GetPlayers.php
,则两个页面不会共享同一会话,因此当脚本检查if (isset($_SESSION['username'])) {.....}
时,它将失败。