我有一个AJAX会话,在页面加载时调用一次,然后在单击后再次调用。它没有第二次进行状态改变所以我决定通过在函数中放置一个警告框来测试它。警报框显示在页面加载上。但是在点击它没有显示 - 得到这个 - 即使PHP端执行。更令人费解的是,如果我尝试测量就绪状态它永远不会出现(不是0,1,2,3或4 - 警报框甚至不会显示),而且我没有得到返回文本。
我最终想要实现的是xmlhttp.responseText返回一个类似于页面加载的值。我错过了什么?
JavaScript的:
function ajaxSession()
{
alert();
xmlhttp = undefined;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
z = xmlhttp.responseText;
}
}
}
function stateCheck()
{
ajaxSession();
xmlhttp.open('POST', thisurl + '/favoritecheck.php',false);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send("0=" + perform + "&1=" + thisplace + ",&2=" + thisusername);
}
function firstCheck()
{
perform = 0;
stateCheck();
if (z == 'found')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-on.png";
document.getElementById("favtext").innerHTML="This is a favorite!";
}
if ( z == 'nouser')
{
perform = 1;
stateCheck();
}
}
function heartCheck()
{
perform = 2;
stateCheck();
if (z == 'added')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-on.png";
document.getElementById("favtext").innerHTML="This is a favorite!";
}
if (z == 'subtracted')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-off.png";
document.getElementById("favtext").innerHTML="Add to your favorites.";
}
}
if (loggedin == 1)
{
document.writeln('<img id="favorite" style="cursor: pointer;" onclick="heartCheck()" src="http://www.********.com/images/favorite-off.png" alt="Favorite" />'
+ '<br />'
+ '<div id="favtext" style="color: #D20425;">'
+ 'Add to your favorites.'
+ '</div>');
firstCheck();
} else if (loggedin == 0)
{
document.writeln('<img id="favorite" style="cursor: pointer;" src="http://www.********.com/images/favorite-off.png" alt="Favorite" />'
+ '<br />'
+ '<div id="favtext" style="color: #D20425;">'
+ '<a style="color: #800000; font-weight: bold;" href="' + thisurl + '/wp-login.php">Log in</a> to add favorites.'
+ '</div>');
}
PHP:
<?php
include('connect.php');
$salt = "********";
$perform = $_POST[0];
$place = $_POST[1];
$user = $_POST[2];
$usercrypt = crypt(md5($user),$salt);
$placeid = trim($place,",");
function checkNow()
{
global $usercrypt;
global $place;
global $conn;
$urow = mysqli_query($conn, "SELECT Users.User FROM Users WHERE Users.User='" . $usercrypt . "';");
if (mysqli_num_rows($urow) > 0)
{
$favcheck = mysqli_query($conn, "SELECT Users.Favorites FROM Users WHERE Users.User='" . $usercrypt . "';");
$favcheck = mysqli_fetch_array($favcheck);
$favcheck = $favcheck[0];
if (strpos($favcheck, $place) !== false)
{
$answer = 'found';
}
else
{
$answer = 'notfound';
}
}
else
{
$answer = 'nouser';
}
return array($answer,$favcheck);
unset($answer);
}
if ($perform == "0")
{
$sendback = checkNow();
echo $sendback[0];
unset($sendback);
}
if ($perform == "1")
{
global $usercrypt;
global $conn;
mysqli_query($conn, "INSERT INTO Users (User) VALUES ('" . $usercrypt . "')");
}
if ($perform == "2")
{
$sendback = checkNow();
global $place;
global $placeid;
global $usercrypt;
global $conn;
$currentnum = mysqli_query($conn, "SELECT Places.Favorites FROM Places WHERE Places.PlaceID=" . $placeid);
$currentnum = mysqli_fetch_array($currentnum);
$currentnum = $currentnum[0];
if ($sendback[0] == 'found')
{
$currentnum--;
$change = str_replace($place,'',$sendback[1]);
mysqli_query($conn, "UPDATE Users SET Favorites='" . $change . "' WHERE User = '" . $usercrypt . "'");
mysqli_query($conn, "UPDATE Places SET Places.Favorites=" . $currentnum . " WHERE Places.PlaceID =" . $placeid);
$answer = 'subtracted';
}
if ($sendback[0] == 'notfound')
{
$currentnum++;
$change = $sendback[1] . $place;
mysqli_query($conn, "UPDATE Users SET Favorites='" . $change . "' WHERE User = '" . $usercrypt . "'");
mysqli_query($conn, "UPDATE Places SET Places.Favorites=" . $currentnum . " WHERE Places.PlaceID =" . $placeid);
$answer = 'added';
}
return $answer;
unset($answer);
}
unset($_POST);
?>
答案 0 :(得分:2)
在 xmlhttp对象收到readystate更改之前,将评估z
的值。您需要将处理返回值的所有代码放入onreadystatechange
函数本身,因为这是唯一保证在收到异步响应后调用的函数。
你可以这样做:
var xmlhttp = false;
// The rest of your code, but remove the `onreadystatechange` assignment from ajaxSession()
// ...
// ...
function heartCheck() {
perform = 2;
stateCheck();
xmlhttp.onreadystatechange = function() {
z = xmlhttp.responseText;
if (z == 'added')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-on.png";
document.getElementById("favtext").innerHTML="This is a favorite!";
}
if (z == 'subtracted')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-off.png";
document.getElementById("favtext").innerHTML="Add to your favorites.";
}
}
}
每次你想要评估AJAX响应时,你都需要做这样的处理程序。
如上所述,在脚本开头声明全局变量也是最清楚的 - 正如@jeroen所提到的,它没有明确要求,但它很好练习并将帮助您跟踪范围。令人困惑的是,z
仅在xmlhttp.onreadystatechange
函数中定义,但您在整个脚本中全局使用它。因此,一个简单的提示是将var z = ''
放在JavaScript的开头,以使您的意图更加清晰(对您自己和可能正在查看您的代码的其他人而言:) :()
答案 1 :(得分:1)
这有点混乱:你正在以一种你永远不会知道什么是什么以及你处于什么状态的方式混合异步和同步javascript。除此之外你使用全局javascript变量你重置和覆盖在将它们用于异步请求时同步。
检查您的firstCheck()
函数:这将重置您的xmlhttp
变量(在另一个函数中......)并发出异步请求,但您已经在检查异步请求的返回值在检查z
值时,在下一行中。该值(另一个全局变量......)将仅在异步调用完成时设置,以便逻辑没有位置。
您需要重新考虑您的体系结构,请记住,每次您发出ajax请求时,结果都无法立即生效,单独的事件将会触发 - readyState
更改 - 只有这样才能执行你想用服务器返回的信息做的事情。