【问题标题】:random quote generator with php, ajax and mysql带有 php、ajax 和 mysql 的随机报价生成器
【发布时间】:2011-08-18 19:38:08
【问题描述】:

我尝试使用this code 和this 来制作随机报价生成器,但它没有显示任何内容。我的问题是:

  • 我的代码有什么问题?

  • 在上面的 tut 中,报价是在单击按钮时生成的,我想 每显示一个随机报价 自动30分钟。我该怎么办 这个?

/////////////////////

quote.html:

<!DOCTYPE html>
<script src="ajax.js" type="text/javascript"></script>
<body>

<!–create the div for the quotes land–>
<div id="quote"><strong>this</strong></div>
<div><a style="cursor:pointer" onclick="run_query();">Next quote …</a></div>

</body>
</html>

///////////////////

quote.php:

<?php
include 'config.php';

// 'text' is the name of your table that contains
// the information you want to pull from
$rowcount = mysql_query("select count(*) as rows from quotes");

// Gets the total number of items pulled from database.
while ($row = mysql_fetch_assoc($rowcount))
{
 $max = $row["rows"];
}

// Selects an item's index at random 
$rand = rand(1,$max)-1;
$result = mysql_query("select * from quotes limit $rand, 1");

$row = mysql_fetch_array($result);
$randomOutput = $row['storedText'];

echo '<p>' . $randomOutput . '</p>';

///////////

ajax.js:

var xmlHttp


function run_query() {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("This browser does not support HTTP Request");
return;
} // end if
var url="quote.php";
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
} //end function

function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("quote").innerHTML=xmlHttp.responseText;
} //end if
} //end function

function GetXmlHttpObject() {
var xmlHttp=null;
try {
// For these browsers: Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
//For Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
} //end function

【问题讨论】:

  • 只是一个建议,“quote.php”文件可以简化为select * from quotes limit 1 order by rand()
  • 嘿!只是一个建议:您可以使用 JavaScript 数组来简化事情。 MySQL 很棒,但是显示这么少量的数据就有点过分了。另外,onClick 有点老派,我建议尝试一下 jQuery,处理程序和基于 CSS 的命名系统是奇迹。
  • 我试过了。不显示任何内容。
  • 凯尔,你能给我举个例子吗?我在 mysql 中拥有的引号数据库不是少量数据,我不想在 javascript 数组中手动​​输入 100 个引号。 .有什么建议吗?

标签: php javascript jquery html ajax


【解决方案1】:

尝试打印 $max、$rand 和 $result 的值。您可以使用 print_r 从 php 页面获取更多信息。

在浏览器上运行 quote.php 以查看是否得到输出。 然后进入ajax调试。

您可以在 ajax 中使用计时器来自动执行每 30 分钟左右的请求。为此使用 javascript 的 settimeout 函数。

HTH

【讨论】:

  • 我在浏览器上运行了 quote.php,但我没有得到任何输入。我的 php 代码有问题吗?
  • 有什么数据可以开始吗?我认为您需要调试才能弄清楚发生了什么。
猜你喜欢
  • 1970-01-01
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-06
  • 2022-01-21
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多