为什么这个Ajax需要很长时间才能渲染?

时间:2012-04-18 01:59:14

标签: php javascript mysql ajax setinterval

我的网页主要由Ajax生成动态内容。它每30秒随机一次,并显示数据库中的新内容。 PHP似乎很好,但是我的Javascript代码似乎有问题,或者数据库出现问题导致它滞后(Ajax加载大约需要30秒!) />在我的Javascript中对setInterval的递归调用似乎在 执行函数之前等待分配的毫秒 ,但我可以在我的Javascript中找不到任何错误。

另外,从数据库中检索到两个图像URL字符串,并且当它必须从外部源检索信息时,Ajax会滞后似乎是合理的。或者也许我使用PHP时存在滞后 - MySQL语法ORDER BY rand()

这是相关的html:
< / p>

    <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
?>

2 个答案:

答案 0 :(得分:3)

您没有在onload方法中运行代码。 AJAX设置代码可能比页面加载的速度更快,因此var products = ...为空。您需要执行以下操作:

<body onload='setIntervalOnload();'>

 window.onload = setIntervalOnload;

答案 1 :(得分:0)

setInterval不会立即调用该函数。该函数的第一次运行将延迟一段时间。

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