JavaScript ajax不起作用

JavaScript ajax is not working

本文关键字:不起作用 ajax JavaScript      更新时间:2024-04-19

下面的代码显示了一个ajax更新的sql表。页面现在加载到一个显示标题行的空白表中。我很难理解为什么这不会渲染表格。没有引发错误。

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
        </script>
        <script>
            setInterval(function() {
                refreshTable();
            }, sleepTime);
            /*creates function refreshTable which uses javascript to post data to sqlAjax.php*/
            function refreshTable() {
                sleepTime = 5000;
                $.ajax({
                    type: "post",
                    url: "sqlAjax.php",
                    data: $(this).serialize(),
                    success: function(data) {
                        //console.log(data); // "something"
                        updateTable(data);
                    }
                });
            }
            /*creates function updateTable that appends the body of the table*/
            function updateTable(tableData) {
                $("#priceTable tbody tr").empty();
                var $tr = $(tableData);
                $('#priceTable > tbody:first').append($tr);
            }
        </script>
        <style type="text/css">
            table {
                width:80%;
                border-collapse:collapse;
            }
            th {
                background:#95bce2;
                color:white;
                font-weight:bold;
            }
            td, th {
                padding:6px;
                border:1px solid #95bce2;
                text-align:left;
            }
            .even {
                background-color:#ecf6fc;
            }
            .odd {
                background-color:white;
            }
            .hover {
                background-color:#ccc!important;
            }
            .focus {
                background-color:#6ab9d0!important;
                color:white;
            }
            â
        </style>
    </head>
    <body>
        <div span class="span4">
            <table id='priceTable'>
                <thead>
                    <tr>
                        <td>Order ID</td>
                        <td>Status</td>
                        <td>Date</td>
                        <td>DID</td>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </body>
</html>

将sleepTime声明作为全局变量,以便所有函数都能看到它

var sleepTime=5000;

setInterval(function(){refreshTable();},sleepTime);

为什么您需要setTimeout?加载页面时运行代码?如果是这样,您应该使用$(document).ready(function() { ... code here ... });方法。