2012-04-18 109 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

相關問題