2012-04-18 111 views
2

我有一个页面,主要是由Ajax生成的动态内容。它每30秒随机化一次,并从数据库中出现新内容。 PHP似乎很好,但或者似乎有我的Javascript代码有问题,或者数据库有问题导致它滞后(Ajax需要大约30秒才能加载!)

看起来好像递归调用到setInterval在我的Javascript中等待分配毫秒之前执行该功能,但我无法在我的Javascript中找到任何错误。

此外,从数据库中检索到两个图像url字符串,并且似乎有理由认为Ajax在必须从外部来源检索信息时会滞后。

或者,也许我的PHP-MySQL语法的使用存在滞后性ORDER BY rand()

下面是相关的html:
这个Ajax为什么需要这么长时间才能呈现?

<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 = "==>&nbsp;" + category + "&nbsp;&nbsp;==>&nbsp;" + 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 
?> 
+1

'为了()'是出了名的慢,做的任意列一个简单的测试和秩序,看看您的问题不见了。 – 2012-04-18 02:02:14

+1

你没有在onload方法中运行你的代码。 AJAX设置代码运行速度可能比页面加载速度快,所以'var products = ...'为空。尝试使用控制台在Chrome中运行(CTRL + SHIFT + J)并查看是否记录了任何错误消息。 – mellamokb 2012-04-18 02:08:43

+0

好的,谢谢,已经在控制台中运行Chrome,并显示如下错误消息:'无法加载资源:服务器响应状态为404(未找到)','Uncaught ReferenceError:$未定义'未捕获的TypeError:无法设置null的属性'innerHTML'...所以它看起来好像'var products'为null。但是,我已经尝试执行Ajax函数本身**第一**,而不是从另一个函数调用它,并没有区别... – 2012-04-18 02:31:55

回答

3

你没有在onload方法中运行你的代码。 AJAX设置代码运行速度可能比页面可以加载的速度快,因此var products = ...为空。你需要做类似如下:兰德公司

<body onload='setIntervalOnload();'> 

window.onload = setIntervalOnload; 
+0

现在,它的工作,谢谢你!我在head部分错误地调用了我的函数'setIntervalOnload()',假设它可能以这种方式渲染得更快,并且没有考虑到它的'依赖页面加载**第一个**(到'getElementById'而不是返回'null')。感谢@NiftyDude,我正在研究rand()命令的替代方法,因为我读的是它很慢。 – 2012-04-18 03:09:20

0

setInterval做不要立即调用该函数。无论间隔多长,函数的第一次运行都会延迟。

如果您希望立即运行以及定时器,您必须自己专门调用该函数。

+0

它立即在'setIntervalOnLoad()'的顶部运行。 – mellamokb 2012-04-18 02:06:28

+0

谢谢,但我在'setInterval'之前先调用了'Ajax'函数,并且由于某种原因,它仍然不会首先执行函数... Ya,@mellamokb刚才说的哈。 – 2012-04-18 02:09:11

相关问题