【发布时间】:2015-08-12 18:34:40
【问题描述】:
我正在使用英特尔 XDK 构建一个简单的应用程序,我需要将我的应用程序连接到一个 mysql 数据库。因为英特尔 XDK 不允许 PHP 文件,所以我需要通过 javascrap 和 json 将我的 html 连接到 php。
这是我找到并编辑的 PHP 代码,它将 PHP 数组作为 JSON 对象发送到英特尔 XDK 应用程序:
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT * FROM quotes LIMIT 1";
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
$jsonData = $row;
}
/* free result set */
mysqli_free_result($result);
//encode to JSON format
echo "<h1>" . json_encode($jsonData) . "</h1>";
}
else {
echo "<h1>" . json_encode($jsonData) . "</h1>";
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
我的 index.html 有以下代码:
<head>
<script>
function GetQuote() {
var xmlhttp;
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)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://domain/db.php?get_rows=json", false);
xmlhttp.send();
}
</script>
</head>
<body onload="GetQuote()">
<div id="quote"> </div>
</body>
我的代码正在运行,我的应用程序在我的表格中显示了最新的一行。问题是这段代码返回了整行,所以我在屏幕上得到了这样的结果: [“列 1”,“列 2”]。我需要的是“Column1”作为记录和“column2”作为记录。
谁能帮帮我?我整天都在解决这个问题,但找不到解决方案。谢谢!
这是我现在的代码:
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxx", "xxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
我现在只是得到一个带有 [null,null] 的空白屏幕。任何人都知道这段代码有什么问题吗?我试过调试,但我是 PHP 新手,我无法让它工作。谢谢!
【问题讨论】:
-
您通过在其周围放置 html 标签来使您自己的 json 无效。你应该只输出 json 而没有别的。
-
使用 column1 和 column2 名称来获取查询中的结果,而不是使用星号 (*),将每个列值保存在一个数组中并将该数组转换为 json 并返回:)
-
@MTahir 我需要怎么做?抱歉,这已经是漫长的一天,我真的希望它能够工作.. :)
标签: javascript php html mysql json