Ajax成功,如何每分钟刷新响应 [英] Ajax success, how to refresh response every minute

查看:124
本文介绍了Ajax成功,如何每分钟刷新响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对应该运行的几行代码感到非常困惑.使用.html时Div会更新,但使用自定义脚本时div不会更新.

I am really confused by this few lines of code that should work in my opinion. Div is updating when using .html, but not when using custom script.

我有几个文件,index.php和test.php

I have a couple files, index.php and test.php

索引包含:

$(document).ready(function () {
    setInterval(function () {
        $(function () {
            $.ajax({
                url: 'test.php',
                dataType: 'json',
                cache: false,
                success: function (data) {
                    // custom script that displays parsed info goes here, doesn't work
                    $("#div").html(data); // works and updates
                }
            });
        });
    }, 10000);
});

test.php包含json字符串.

test.php contains json string.

index.php可以很好地显示并更新div中已解析的信息,但是使用json填充的数据的脚本不会刷新.

index.php displays, and updates the parsed info in a div just fine, however the script using the data populated by json doesn't refresh.

任何帮助将不胜感激.

谢谢

推荐答案

使用setInterval,每隔一定时间调用该函数,当您使用setTimeout调用该函数时,您的函数可能会或可能不会完全执行,就有机会完全执行代码.好吧,在您的问题中,我正在编写一个自执行的匿名函数,函数名称为request,我将在每个 10000 milli seconds

Using setInterval, calls the function at regular intervals of time, your function may or may-not execute completely , when you call the function using setTimeout, there is a chance for executing of code (completely). well In your question, I'm writing a self executing anonymous function with a function name as request and I'm gonna call it after every 10000 milli seconds

$(function () {
    (function request() {
        $.ajax({
            url: 'test.php',
            dataType: 'json',
            cache: false,
            success: function (data) {
                $("#selector").html(data); // works and updates
            }
        });
         //calling the anonymous function after 10000 milli seconds
        setTimeout(request, 10000);  second
    })(); //self Executing anonymous function
});

只需尝试一下=)

这篇关于Ajax成功,如何每分钟刷新响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆