1

我有一个基于 Django 的 Web 应用程序。我使用Scrapy Crawler来抓取网页。目前,我的目标是能够使用 jQuery 和 AJAX 请求从网页中控制爬虫。

我的理论设置如下:

  • 在网页上,我有一个按钮。当我单击按钮时,爬虫在服务器端启动。
  • 爬虫启动后,我会定期向服务器发送 AJAX GET 请求,window.setInterval以了解到目前为止已爬取了多少网页。
  • 爬虫完成后,GET 请求应使用window.clearInterval.

这些是我当前代码中的相关行:

$(document).ready(function() {

    // This variable will hold the ID returned by setInterval
    var monitorCrawlerId;

    $startCrawlerButton.on('click', function(event) {

        // This function should be run periodically using setInterval
        var monitorCrawler = function() {

            $.ajax({

                type: 'GET',
                url: '/monitor_crawler/',
                // ...
                success: function(response) {

                    // if the server sends the message that the crawler
                    // has stopped, use clearInterval to stop executing this function
                    if (response.crawler_status == 'finished') {

                        clearInterval(monitorCrawlerId);

                    }

                } 

            });

        };

        // Here I send an AJAX POST request to the server to start the crawler
        $.ajax({

            type: 'POST',
            url: '/start_crawler/',
            // ...
            success: function(response) {

                // If the form that the button belongs to validates correctly,
                // call setInterval with the function monitorCrawler defined above
                if (response.validation_status == 'success') {

                    monitorCrawlerId = setInterval('monitorCrawler()', 10000);

                }

            }

        });

    });
});

问题:当我执行这段代码时,我在 Firefox 的 web 控制台中得到了这个:

ReferenceError: monitorCrawler is not defined

然而,奇怪的是,该函数monitorCrawler无论如何都会定期执行。但是每次执行时,我都会再次收到相同的错误消息。如果我把它放在monitorCrawler外面,$startCrawlerButton.on()我仍然会得到同样的错误。我该如何解决这个问题?由于我是 JavaScript 新手,因此感谢您提供任何帮助。非常感谢你!

4

3 回答 3

3

setIntervalwindow,当第一个参数是字符串时,在全局 ( ) 上下文中解析。您可以给它一个指向要调用的函数的变量,甚至:

setInterval(function(){monitorCrawler();}, 10000);

这将创建一个闭包,其中局部变量monitorCrawler在间隔触发时仍然存在。

于 2012-11-22T19:51:10.430 回答
2

改变

setInterval('monitorCrawler()', 10000);

setInterval(monitorCrawler, 10000);

永远不要将字符串传递给setInterval, 但函数引用!它们eval每次都会被编辑,并且在全局范围内 - 但是您的monitorCrawler函数对于点击处理程序来说是本地的(我猜“把它放在外面”你的意思是“进入就绪回调”)。

于 2012-11-22T19:48:47.200 回答
1

尝试

monitorCrawlerId = setInterval(monitorCrawler, 10000);

带参数:

monitorCrawlerId = setInterval(function(){
      //prepare params.
      monitorCrawler(/* param1, param2*/);
   }, 10000);
于 2012-11-22T19:47:26.727 回答