代码之家  ›  专栏  ›  技术社区  ›  Rye

通过js获取分隔符文本和显示之间的html

  •  0
  • Rye  · 技术社区  · 1 年前

    我试图通过JS在两个分隔符(此处为“工具”和“爱好”)之间获取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做好自己的工作?

    1 回复  |  直到 1 年前
        1
  •  2
  •   tom    1 年前

    我感觉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);
      });