0

我正在尝试使用 setInterval 每 5 秒刷新一次页面数据。我有一个简单的 html 表单,其中包含一个 ID 为“名称”的文本框。我也有一个提交按钮,它工作正常(代码也在下面),但我无法让页面自己发布。所有帮助表示赞赏。

<script type="text/javascript" src="/media/jquery-1.10.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
    window.setInterval(function() {
        AutoPost();
    }, 5000);
});

function AutoPost() {
    $.ajax({
        // post the form values via AJAX…
        var postdata = {name: $("#name").val()} ;
        $.post('/submit', postdata, function(data) {
            // and set the title with the result
            $("#title").html(data['title']) ;
           });
        return false ;
        });
    });
}


$(function() {
// When the testform is submitted…
$("#testform").submit(function() {
    // post the form values via AJAX…
    var postdata = {name: $("#name").val()} ;
    $.post('/submit', postdata, function(data) {
        // and set the title with the result
        $("#title").html(data['title']) ;
       });
    return false ;
    });
});

4

2 回答 2

0

$.post并且$.get只是更结构化的简写版本$.ajax(),所以我更喜欢使用后者。额外的结构让我保持直截了当。

这是您的示例的工作版本:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {

                window.setInterval(function() {
                    AutoPost();
                }, 3000);

            }); //END $(document).ready()

            function AutoPost() {
            //  var myName = $("#name").val();
                $.ajax({
                    type: "POST",
                    url: "test134b.php",
            //      data: 'name=' + myName,
                    success: function(data) {
                        $("#title").html(data) ;
                    }

                });
            } //END fn AutoPost

        </script>
    </head>
<body>
    Current Time:<br />
    <div id="title"></div>
</body>
</html>

下面是一些简单的 AJAX 构造的附加示例:

一个简单的例子

更复杂的例子

根据下拉列表 1 中的选择填充下拉列表 2

于 2013-08-09T17:15:58.257 回答
0
<script type="text/javascript" src="/media/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    function autoPost(e) {
        if (e) e.preventDefault();
        var postdata = {name: $("#name").val()} ;
        $.post('/submit', postdata, function(data) {
            $("#title").html(data['title']) ;
        });
    }

    $(function() {
        $("#testform").on('submit', autoPost);
        setInterval(autoPost, 5000);
    });
</script>
于 2013-08-09T17:07:05.797 回答