php - 为什么这个 Ajax 渲染需要这么长时间?

标签 php javascript mysql ajax setinterval

我有一个页面,主要包含由 Ajax 生成的动态内容。每 30 秒进行一次随机化,并出现数据库中的新内容。 PHP 看起来不错,但我的 Javascript 代码似乎有问题,或者数据库存在问题导致其滞后(Ajax 需要大约 30 秒)加载!)

在我的 Javascript 中,对 setInterval 的递归调用似乎正在等待分配的毫秒之前 strong> 执行该函数,但我在 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 = "==>&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
?>

最佳答案

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

<body onload='setIntervalOnload();'>

 window.onload = setIntervalOnload;

关于php - 为什么这个 Ajax 渲染需要这么长时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10201783/

相关文章:

php - 在具有重复项的单列上插入多行

php - MySQL JSON 存储与两个表

javascript - 使用 Node.js 将数据库查询发送到网站

php - 检查一个类是否是另一个类的子类

php - mysql 查询 - ORDER BY Case 条件

javascript - 单击内存游戏的第一张牌时启动计时器

Javascript/Jquery 3.3 从非严格到严格和顺序调用的转换函数

javascript - React的生命周期方法是自动绑定(bind)的吗?如果不是,我们应该用 .bind(this) 绑定(bind)它们吗?

mysql - 如果日期列和字符串 "-"为 null 时返回日期,并且仍然作为日期而不是字符串传递给前面

mysql - 交换两个不同表的两列的值