使用AJAX从MySQL数据库检索数值数据

Retrieving Numerical Data from MySQL Database using AJAX

本文关键字:检索 数值数据 数据库 MySQL AJAX 使用      更新时间:2023-09-26

晚上好。我正在使用CANVAS、PHP、MySQL和AJAX创建一个游戏。这是一个非常简单的游戏:它由一块8格高、8格长的棋盘组成(就像棋盘一样)。用户应该点击任何一个方块,他/她点击的方块将以(xpos,ypos)的形式存储在数据库中。当然,数据库存储在服务器端,html游戏在客户端运行,所以我需要AJAX在javascript和php之间进行交互。我做了这份工作,一切都很顺利。

当我试图加载Board时,我的问题就出现了。想象一下,我们的数据库中有下一个数据:

(行)。。。(导出)。。。(ypos)

1 1 2

2 3 2

3 6 5

当用户打开游戏时,我需要它通过从数据库中检索(xpos,ypos)数据来将这个位置加载到棋盘上。我尝试的代码看起来像这样:

Game.html

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Basic Game</title></head>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded () {
    requestXMLLoadGems();
}
function requestXMLLoadGems() {
    var xmlhttp;
    if ( window.XMLHttpRequest ) { // IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { 
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","download_gems.php", true);
    xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 &&  xmlhttp.status == 200) {
        mycoords=xmlhttp.responseText;
        document.write(mycoords);
    }
    }
    xmlhttp.send(null);
}
</script>
<body></body>
</html>

服务器端文件"download_gems"如下所示:

download_gems.php

<?php
// Open a MySQL connection
$dbinfo = 'mysql:host=localhost;dbname=mydb';
$user = 'root';
$pass = '';
$link = new PDO($dbinfo, $user, $pass) or die('Error connecting database');
// Create and execute a MySQL query
$sql = "SELECT xpos,ypos FROM board";
foreach($link->query($sql) as $row) {
    $entries[]=array($row['xpos'], $row['ypos']);
}
print_r($entries);
?>

一切都很好。除了我需要检索数值数据(xpos,ypos),而不是字符串数据我的问题是如何使用:检索数值数据

xmlhttp.responseText;

我哪儿也找不到答案!

如果有任何帮助,我将不胜感激。非常感谢。

不要使用print_r(),而是使用json_encode()并使用json内容类型头发送输出。然后在客户端使用JSON解析器。例如,如果您使用jQuery的ajax功能,jQuery会自动将有效的JSON转换为JavaScript对象。

无关:您将无法(也不希望)为此(或任何事情!)使用document.write()。