【发布时间】:2012-04-29 09:58:21
【问题描述】:
我的页面主要包含由Ajax 生成的动态内容。它每 30 秒随机一次,并且会出现来自数据库的新内容。 PHP 看起来不错,但我的 Javascript 代码似乎有问题,或者数据库有问题导致它滞后(加载 Ajax 大约需要 30 秒!)
似乎在我的 Javascript 中对 setInterval 的递归调用正在等待分配的毫秒 执行该函数,但我在我的 Javascript 中找不到任何错误.
此外,从数据库中检索到两个图像 url 字符串,当 Ajax 必须从外部来源检索信息时,它似乎会滞后。
或者可能存在滞后在我使用 PHP-MySQL 语法 ORDER BY rand()?
这里是相关的 html:
<html>
<head>
<title></title>
<script type = "text/javascript" src = "randomProducts.js" />
<script type = "text/javascript">
setIntervalOnload();
</script>
</head>
<body>
...
...
...
</body>
</html>
这里是相关的 Javascript:
// global static variables
var subCategory; // initialized from setCategoryTree
var t; // for setInterval and clearInterval
var seconds;
var millisecondsPerSecond;
var milliseconds;
function setIntervalOnload()
{
getRandomProducts();
if(typeof t != "undefined")
clearInterval(t);
seconds = 30;
millisecondsPerSecond = 1000;
milliseconds = seconds * millisecondsPerSecond;
t = setInterval(getRandomProducts, milliseconds);
}
function getRandomProducts()
{
//window.alert(subCategory);
if(typeof subCategory == "undefined")
subCategory = "all";
else
{
clearInterval(t);
t = setInterval(getRandomProducts, milliseconds);
}
var req = new XMLHttpRequest();
var products = document.getElementById("products");
req.onreadystatechange = function()
{
if( (req.readyState == 4) && (req.status == 200) )
{
var result = req.responseText;
products.innerHTML = result;
}
};
req.open("GET", "randomProducts.php?category=" + subCategory, true);
req.send(null);
}
function setCategoryTree(link)
{
var categoryTree = document.getElementById("categoryTree");
/* climbing the DOM-tree to get the category name (innerHTML of highest "a" tag) */
var category = link.parentNode.parentNode.parentNode.getElementsByTagName("a")[0].innerHTML;
subCategory = link.innerHTML;
categoryTree.innerHTML = "==> " + category + " ==> " + subCategory;
getRandomProducts();
}
...这里是相关的 PHP:
<?php
// connect to MySQL
$dbName = "blah";
$db = mysql_connect("localhost", $dbName, "asdf");
if (!$db)
{
echo "<p>Error - Could not connect to MySQL</p>";
exit;
}
// select the blah database
$blah = mysql_select_db("blah");
if(!$blah)
{
echo "<p>Error - Could not select the blah database.</p>";
exit;
}
// fix html characters in $subCategory
$subCategory = $_GET["category"];
trim($subCategory);
$subCategory = stripslashes($subCategory);
$subCategoryFixed = htmlspecialchars($subCategory);
// for loop for each random product (total of 10 random products)
for($i = 0; $i < 10; $i++)
{
// query the blah database for all products
if($subCategoryFixed == "all")
{
$query = "SELECT * FROM products ORDER BY rand();";
$result = mysql_query($query);
}
else // query the blah database for products in selected subCategory
{
$query = "SELECT * FROM products WHERE cat = " . $subCategoryFixed . " ORDER BY rand();";
$result = mysql_query($query);
}
if (!$result)
{
echo "<p>Error - the query could not be executed</p><br />";
$error = mysql_error();
echo "<p>" . $error . "</p>";
exit;
}
$row = mysql_fetch_array($result);
$productValues = array_values($row);
$name = htmlspecialchars($productValues[3]);
$price = htmlspecialchars($productValues[5]);
$img = htmlspecialchars($productValues[7]);
// product info is formatted for home.html here
$str = '<div>
<a href = "' . $link . '" title = "' . $name . '">
<table id = "product-table" onmouseover = "darkenProduct(this);" onmouseout = "lightenProduct(this);">
<tr>
<td>' . $name .'</td>
</tr>
<tr>
<td><img src = "' . $img . '" /></td>
</tr>
<tr>
<td>' . $price . '</td>
</tr>
</table>
</a>
</div>';
echo $str;
} // end of products for loop
?>
【问题讨论】:
-
order by rand()是出了名的慢,做一个简单的测试并按任意列排序,看看你的问题是否消失了。 -
您没有在 onload 方法中运行您的代码。 AJAX 设置代码的运行速度可能比页面加载速度快,因此
var products = ...为空。尝试使用控制台 (CTRL+SHIFT+J) 在 Chrome 中运行,看看是否记录了任何错误消息。 -
好的,谢谢,已在 Chrome 中使用控制台运行此程序,并显示以下错误消息:
Failed to load resource: the server responded with a status of 404 (Not Found)、Uncaught ReferenceError: $ is not defined、Uncaught TypeError: Cannot set property 'innerHTML' of null... 所以看起来var products是空值。但是,我尝试过first执行Ajax函数本身,而不是从另一个函数调用它,没有区别... -
不,您需要执行
<body onload='setIntervalOnload();'>或window.onload = setIntervalOnload;之类的操作才能使其仅在文档完全加载后运行。 -
您有可以查看的实时站点吗?这样可能更快:)
标签: php javascript mysql ajax setinterval