我有一個基於Django的Web應用程序。我使用Scrapy Crawler來抓取網頁。目前,我的目標是能夠使用jQuery和AJAX請求從網頁內控制抓取工具。如何解決此ReferenceError?
我的理論體系如下:
- 在網頁上,我有一個按鈕。當我點擊按鈕時,爬蟲程序在服務器端啓動。
- 抓取工具啓動後,我會定期通過
window.setInterval
向服務器發送AJAX GET請求,以瞭解到目前爲止已抓取了多少個網頁。 - 一旦爬蟲完成,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
無論如何得到定期執行。但每次執行時,我都會再次收到相同的錯誤消息。如果我在$startCrawlerButton.on()
之外放monitorCrawler
,我仍然會得到相同的錯誤。我該如何解決這個問題?由於我是一個JavaScript新手,任何幫助表示讚賞。非常感謝你!
謝謝,伊戈爾。 :)這正是我需要的。通過這種方式,我可以將參數添加到'monitorCrawler()'中,在我的情況下這是必需的。由於您是第一個發佈此特定解決方案的人,因此我接受您的答案。 – pemistahl