-2

如何递归调用 jQuery 插件?我有一个名为poll.jsmain.php 的文件。我制作了一个名为pollcall的插件order_provider.php来捕获登录商店的新订单。poll如果注册了新订单,该功能应每 15 秒检查一次。我需要poll递归调用。我做了这样的插件:

(function($){
    $.fn.poll = function (shopid){
           $.getJSON("order_provider.php?looking=all&shopid="+shopid, function(data){
              // Do Something
           }).done(function(){
              // Do Something
              setTimeout(poll(shopid),15000)
           })
    }
 })(jQuery);

但它只工作一次!

4

2 回答 2

0

实施的问题很少

  1. setTimeout 需要一个函数引用作为参数

工作版本可能类似于

(function ($) {


    $.fn.poll = function (shopid) {
        function poll() {
            $.getJSON("order_provider.php?looking=all&shopid=" + shopid, function (data) {
                // Do Something
            }).done(function () {
                // Do Something
                setTimeout(poll, 15000)
            })
        }

        poll();
    }
})(jQuery);

注意:不想让它像一个完整的插件......只是修复现有版本中的一些问题

于 2013-10-21T08:12:08.213 回答
0

那是因为setTimeout只工作一次,试试吧setInterval。这里是

所以我认为它应该看起来像这样,我还没有测试过..但也许可以让你开始或了解如何进行工作

//the shop id it is to check if the users is login...
// this ajax call is used for gettings new items for that client
//set the php value for a hidden field
$(document).ready(function(){

/*
    (function($) {
        var shopid = document.getElementById("userid").value;
        $.fn.poll = function(shopid) {
            $.getJSON("order_provider.php?looking=all&shopid=" + shopid, function(data) {}).done(function() {
                var shopinterval = setInterval(function(shopid) {
                    $(this).poll(shopid);
                }, 15E3);
            }).fail(function(shopid) {
                errorhandler(shopid);
            });
        }
        $.fn.errorhandler = function(shopid) {
            clearInterval(shopinterval);
            //try again
            console.log("error");
            poll(shopid);
        }
    })(jQuery);
*/
    var shopid = document.getElementById("userid").value;

    if(shopid != null || shopid != null || shopid != undefined){
        setInterval(function(shopid){
            poll(shopid);
        }, 15E3);
    }  

    function poll(userId){  
        $.getJSON("order_provider.php?looking=all&shopid=" + shopid, function(data) {}).done(function() {
            var shopinterval = setInterval(function(shopid) {
                $(this).poll(shopid);
            }, 15E3);
        }).fail(function(shopid) {
            errorhandler(shopid);
        });
    }

    function errorHandler(userId){
        var confirmation=confirm("Press a button");
        if (confirmation==true){
            clearInterval(shopinterval);
            poll(shopid);
          }else{
             console.log("error");
          }         

    }

});

注意我不确定它是否符合你的意思,但试一试,这也是基于它输出用户ID的php代码,所以不要从php调用javascript(不好的做法),它期望成为一个input领域,隐藏着我们需要的价值......我希望它可以帮助你更多...... ps ..我只是在火车上做的,所以我不知道它是否可以开箱即用。 .. ;)

于 2013-10-21T08:06:41.697 回答