我有一个基于 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 新手,因此感谢您提供任何帮助。非常感谢你!