我正在使用 JQuery 从网页中抓取一些数据,但是当我尝试将值设置为局部变量时,它变得未定义。我已经在 $.get() 方法的范围以及其他实例中搜索了变量在返回时未定义但在打印到控制台时未定义的情况,我已经陷入了死胡同。我有什么遗漏的吗?为什么我不能指向 $.get() 中的变量?
function scrape(url) {
let imageUrl = "";
$.get(url, function(response) {
imageUrl = response.toString().split("<meta property=\"og:image\" content=")[1].split("\"")[1];
console.log(imageUrl); // THIS PART WORKS AND PRINTS DESIRED URL
});
console.log(imageUrl); // this prints nothing...
return imageUrl; // returns undefined...
}
scrape("https://www.instagram.com/p/BfKjQxcgv-E/");
最佳答案
$.get
是异步的。因此,您是否在 $.get
方法返回其响应之前返回空白 imageUrl。
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, data: data, success: success, dataType: dataType });
要调试它并查看它是如何工作的,您可以尝试:
function scrape(url) {
let imageUrl = "";
$.get(url, function(response) {
imageUrl = response.toString().split("<meta property=\"og:image\" content=")[1].split("\"")[1];
console.log(imageUrl); // THIS PART WORKS AND PRINTS DESIRED URL
console.log('Running secondly');
});
console.log('Running first');
console.log(imageUrl); // this prints nothing...
return imageUrl; // returns undefined...
}
解决方案:
使用 $.ajax
并根据需要进行配置,并将 async 设置为 false。或者您可以使用以下方法全局更改 jQuery 的 ajax 设置:
jQuery.ajaxSetup({async:false});
关于javascript 函数返回未定义但 console.log() 打印预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48783189/