提问人: 提问时间:4/16/2022 更新时间:4/16/2022 访问量:414
如何获取脚本标签之间的JSON数据?
How can I get the JSON data between the script tags?
问:
我想获取一个html页面,然后用domParser解析它。然后我想在这个html文件中的脚本标签之间拉取数组。 如何访问此html文件内script标签中的imageUrl?
fetch(geturl)
.then(function(response) {
return response.text();
})
.then(function(html) {
var parser = new DOMParser();
var document = parser.parseFromString(html, "text/html");
// here
})
.catch(function(error) {
console.log("Error: ", error);
});
<script>
let testArray = {"test":"138","test2":95,"imageUrl":"hrththterg122323"};
</script>
答:
2赞
Kevin Mario Gerard
4/16/2022
#1
script 标记中定义的对象会立即初始化。以后初始化或运行的所有其他 js 都可以访问定义的对象。
fetch(geturl)
.then(function(response) {
return response.text();
})
.then(function(html) {
var parser = new DOMParser();
var document = parser.parseFromString(html, "text/html");
console.log(testArray.imageUrl);
})
.catch(function(error) {
console.log("Error: ", error);
});
评论
0赞
4/16/2022
无法获取页面:ReferenceError:未定义 testArray
0赞
4/16/2022
当我在网站上运行它时,我可以按照您所说的访问它,但是当我使用 fetch 执行此操作时,我收到一个未定义的错误。
评论