PHP调用函数从另一个文件无效

时间:2015-06-05 09:30:52

标签: php ajax

基本上,我试图根据另一个文件中函数的返回值在一个文件中设置变量的值。然后通过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

AJAX error message

1 个答案:

答案 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'];
}
...