jQuery的Ajax和间隔 [英] jQuery AJAX with an interval

查看:146
本文介绍了jQuery的Ajax和间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于一个区间内的AJAX调用的问题。为什么它不工作,或工作,它的工作方式。

I have a question about an AJAX call within an interval. And why it doesn't work, or work the way it works.

我有这个code(这其中不工作)

I have this code (this one doesn't work)

setInterval($.ajax({
  //Place code here
}), 2000);

但后来我让这样

but then I make it this way

setInterval(function() {
  $.ajax({
    //Do ajax stuff here
  });
}, 2000);

现在它的工作原理,但对我来说,这看起来像我只是做一个额外的匿名函数。

Now it works, but to me this looks like I only make an extra anonymous function.

推荐答案

的setInterval 需要一个函数或可执行文件code字符串格式。

setInterval requires a function or executable code in string format.

在一个字符串中把第一个电话会工作。

The first call will work when put within a string.

setInterval('$.ajax({ //Place code here })', 2000);

使用这个语法鼓励出于同样的原因与使用评估

的setInterval 也可以采取PARAMS的可选列表。 你可以利用这一点优势,使用这样的:

setInterval can also take an optional list of params. You can take advantage of this fact and use something like this:

setInterval($.ajax/*a reference to the ajax function*/,
 2000, {url: 'someurl', success: onSuccess, error: onError}/*args passed to $.ajax*/
);

请注意,这不会对使用对象方法的工作原理确定的背景下,作为将被绑定到窗口。也就是说,下面是行不通的:

Note that this wouldn't work for object methods that use this to determine the context, as the value of this will be bound to window. That is, the following wouldn't work:

setTimeout($('h1').css, 1000, {'color': 'red'});

这篇关于jQuery的Ajax和间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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