gpt4 book ai didi

javascript - 如何解决这个 ReferenceError?

转载 作者:行者123 更新时间:2023-11-30 08:08:48 30 4
gpt4 key购买 nike

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

我的理论设置如下:

  • 在网页上,我有一个按钮。当我点击按钮时,爬虫在服务器端启动。
  • 爬虫启动后,我会使用 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 无论如何都会定期执行。但是每次执行时,我都会再次收到相同的错误消息。如果我将 monitorCrawler 放在 $startCrawlerButton.on() 之外,我仍然会遇到相同的错误。我该如何解决这个问题?由于我是 JavaScript 新手,我们将不胜感激任何帮助。非常感谢!

最佳答案

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

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

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

关于javascript - 如何解决这个 ReferenceError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13519144/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com