英文:
Fetching html between delimiter text and display via js
问题
我尝试使用JS在两个定界符之间(这里是"tools"和"hobbies")获取HTML,但没有显示任何内容:
fetch('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Cool_Stuff.html')
.then(response => response.text())
.then(data => {
const start = data.indexOf('Tools');
const end = data.indexOf('Hobbies');
const result = data.substring(start, end);
document.getElementById('output').innerHTML = result;
})
我在PHP中成功实现了这个功能:
<?php
$url = 'https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Cool_Stuff.html';
$html = file_get_contents($url);
$start = strpos($html, '<!------Tools--------->');
$end = strpos($html, '<!-----Hobbies---->', $start);
$length = $end - $start;
$result = substr($html, $start, $length);
echo $result;
?>
所以:
如何说服JS执行其任务?
英文:
I attempted fetching html between two delimiters (here "tools" and "hobbies") via JS, but there is nothing displayed:
fetch('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Cool_Stuff.html')
.then(response => response.text())
.then(data => {
const start = data.indexOf('Tools');
const end = data.indexOf('Hobbies');
const result = data.substring(start, end); document.getElementById('output').innerHTML = result;
})
I *do have it working in php:
<?php
$url = 'https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Cool_Stuff.html';
$html = file_get_contents($url);
$start = strpos($html, '<!------Tools---------->');
$end = strpos($html, '<!-----Hobbies---->', $start);
$length = $end - $start;
$result = substr($html, $start, $length);
echo $result;
?>
So:
How can I convince JS to do its job ?
答案1
得分: 2
我有一种感觉,JS 版本的 indexOf
参数与您在 PHP 上使用的参数不同。
这应该可以解决问题:
fetch('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Cool_Stuff.html')
.then(response => response.text())
.then(html => {
const start = html.indexOf('<!--Tools-->');
const end = html.indexOf('<!--Hobbies-->', start);
const result = html.substring(start, end);
console.log(result);
})
.catch(error => {
console.error('Error:', error);
});
英文:
I have the feeling the indexOf parameters for the JS version are different than the ones you using on PHP.
This should do the trick:
fetch('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Cool_Stuff.html')
.then(response => response.text())
.then(html => {
const start = html.indexOf('<!------Tools---------->');
const end = html.indexOf('<!-----Hobbies---->', start);
const result = html.substring(start, end);
console.log(result);
})
.catch(error => {
console.error('Error:', error);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论