我正在创建一个网络游戏,用于学习针对儿童的新单词.
我有一组四个链接,每个链接显示从我的数据库中检索到的特定单词和线索,我需要检查已选择的单词是否与该线索的正确单词匹配.
我知道我需要使用javascript,因为onClick函数,我可以成功检查所选单词是否与正确的单词匹配.但是,如果单词匹配正确,我需要更新数据库中保存的分数,因此我需要使用php.
从我可以收集到的这意味着我必须使用AJAX但我找不到任何人使用AJAX onClick链接然后更新数据库的好例子.
我试图这样做……但它可能是完全错误的,因为我无法让它正常工作:
//This is my link that I need to use in my game.php file where $newarray[0] is that answer I want to check against $newarray[$rand_keys]
$newarray[0]
//我在score.js文件中尝试ajax
var xmlHttp;
function originalUpdateScore(obj,corr){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
if(corr == obj){
var url="getscore.php";
//url=url+"?q="+str;
//url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
//xmlHttp.open("GET",url,true);
xmlHttp.open(url,true);
xmlHttp.send(null);
alert('Correct');
}
else
{
alert('AHHHHH!!!');
}
window.location.reload(true);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
//attempting to update the database in a getscore.php file
//$q=$_GET["q"];
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");
$sql= "UPDATE `temp` SET `tempScore`= `tempScore`+1 WHERE (temp.Username='$_SESSION[logname]')";
$showsql = "SELECT `tempScore` FROM `temp` WHERE (temp.Username='$_SESSION[logname]')";
$result = mysqli_query($con, $showsql);
echo "$result";
mysqli_close($con);
?>