基本上,我试图根据另一个文件中函数的返回值在一个文件中设置变量的值。然后通过AJAX返回,但是,AJAX似乎总是表示错误。代码如下:
updateTurn.php
<?php
//This is called by AJAX
require_once('functions.php'); //include necessary file
$player = getCurrentTurn(); //call function
echo $player;
?>
的functions.php
...
function getCurrentTurn()
{
//the query and connection function appropriately
include_once("getConn.php");
$query = $GLOBALS['conn']->prepare("SELECT turn FROM Game");
$query->execute();
$result=$query->fetch(PDO::FETCH_ASSOC);
return $result['turn']; //return the result of the query
}
...
AJAX
function checkForTurnChange(){
$.ajax({
type:"GET",
url:"updateTurn.php",
async:true,
cache:false,
timeout:10000,
success:function(data){
alert(data);
},
//this is where AJAX is returning
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(textStatus +": "+ errorThrown);
}
});//end AJAX
};//end function
错误是由行$player = getCurrentTurn();
引起的。如果我删除此echo
任何字符串值,那么它可以正常工作。这是非常基本的,但我似乎无法看到我的错误。所有帮助表示赞赏。
编辑:AJAX调用error:
,结果为alert
:
答案 0 :(得分:1)
从include("getConn.php");
中getCurrentTurn()
移除了functions.php
,并将其重新定位为可用于整个文件,而不只是本地可用于该功能。因此,functions.php
应为:
include("getConn.php");
...
function getCurrentTurn()
{
$query = $GLOBALS['conn']->prepare("SELECT turn FROM Game");
$query->execute();
$result=$query->fetch(PDO::FETCH_ASSOC);
return $result['turn'];
}
...