简体   繁体   English

php,ajax和mysql的随机报价生成器

[英]random quote generator with php, ajax and mysql

i've tried using this code and this to make a random quote generator, but it doesn't display anything. 我试过使用此代码使一个随机的报价生成器,但它不显示任何内容。 my questions are: 我的问题是:

  • what is wrong with my code? 我的代码有什么问题?

  • in the above tut, the quote is generated on a button click, i'd like a random quote to be displayed every 30 mins automatically. 在上面的示例中,报价是在单击按钮时生成的,我希望每30分钟自动显示一次随机报价。 how do i do this? 我该怎么做呢?

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

quote.html: 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: 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: 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

Try to print the values for $max,$rand and $result. 尝试打印$ max,$ rand和$ result的值。 You can use print_r to get more info from the php page. 您可以使用print_r从php页面获取更多信息。

Run the quote.php on browser to see if you get an output. 在浏览器上运行quote.php以查看是否获得输出。 Then get to ajax to debug. 然后进入ajax进行调试。

You can use a timer in ajax to automate your requests for every 30 mins or so. 您可以在ajax中使用计时器,每30分钟左右自动执行一次请求。 use javascript's settimeout function for this. 为此使用javascript的settimeout函数。

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM