我正在努力找出为什么我的AJAX函数返回undefined
的原因,我可以通过向函数中添加document.getElementById("aDisplayDiv").innerHTML = characterStatsArray[a]
来将函数输出成功输出到html中的div中,但是我没有这样做希望这样做,我希望函数只输出相关的数组图形,以便可以从中进行计算。
当我刚输出getCharStats(2)
(或任何其他参数)时,结果在页面上显示为undefined
。
JS
function getCharStats(a) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var characterStatsArray = JSON.parse(this.responseText);
return characterStatsArray[a];
}
};
xmlhttp.open("GET", "loadCharacterStats.php", true);
xmlhttp.send();
}
var userHP = getCharStats(3);
document.getElementById("mobhealthbar").innerHTML= "MOB HP: " + mobHP;
PHP
<?php
session_start();
require("db.php");
require("DatabaseObject.php");
$database = new DatabaseObject($host, $username, $password, $database);
$getCharacter = $_SESSION["ActiveCharacter"];
$sessionid = $_SESSION['user_id'];
$sql = $database->query("SELECT `character_name`,`userid`,`character_class`,`level`,`health`,`max_health`,`mana`,`strength`,`constitution`,`wit`,`intelligence` FROM `character` WHERE `userid` = '$sessionid' and `character_name` = '$getCharacter'") or die("Error: ". mysql_error(). " with query ");
while ($row = $sql->fetch_assoc()){
//creates a JSON string to export the character sta
$characterStatsArray = array($row['character_name'],$row['character_class'],$row['level'], $row['level'],$row['health'],$row['mana'],$row['strength'],$row['constitution'],$row['wit'],$row['intelligence']);
$charStatsJSON = json_encode($characterStatsArray);
echo $charStatsJSON;
}
?>
更新
因此,在准备好建议和线程并进一步阅读之后,我已经接受了使用回调的建议,我仍然返回“ undefined”,这是我的回调逻辑错误:|?
我添加的回调如下所示;
更新了JS
function getCharStats(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
callback
}
};
xmlhttp.open("GET", "loadCharacterStats.php", true);
xmlhttp.send();
}
function myCallback(result) {
var characterStatsArray = JSON.parse(this.responseText)
return characterStatsArray[result];
};
getCharStats(myCallback);