jQuery读取.txt文件但获取特定数据

时间:2019-02-10 08:35:22

标签: javascript jquery html arrays object

我正在尝试从.txt文件获取和读取数据,然后在HTML中显示数据。

我当前正在使用以下代码来打印.txt文件的每一行:

$.get('assets/test.txt', function(data) {
    var lines = data.split("\n");
    $.each(lines, function(n, elem) {
        $('#container').append('<div>' + elem + '</div>');
    });
});

这显然会打印出.txt文件的每一行。而我只想从.txt文件中获取特定数据。例如,.txt文件就是这样。

{
"header": "This is me doing a test",
    "menu": [{
        "title":"Home","url":"index.html"
        }, {
            "title":"Page 1",
            "url":"page2.html"
        },{
            "title":"Page 2",
            "url":"page2.html",
            "submenu": [{
                "title":"SubPage 1",
                "url":"subpage1.html"
            },{
                "title":"SubPage 2",
                "url":"subpage2.html"
            }]
        },{
            "title":"Contact",
            "url":"contact.html"
        }
    ],
    "title": "Welcome to our homepage",
    "body": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pharetra sit amet ante at commodo. Sed tincidunt rhoncus fermentum. Donec fermentum volutpat est, a interdum odio scelerisque non. Nullam facilisis magna ac ipsum sollicitudin accumsan. Sed id dui adipiscing, condimentum magna non, molestie ipsum. Donec varius massa eget justo vulputate rhoncus. Integer laoreet turpis id magna rutrum sodales. Nullam eu mauris hendrerit, vulputate nisi ut, condimentum metus. Donec eros ligula, facilisis ac mi a, accumsan vestibulum tortor. Morbi tellus felis, tempor non mi ac, viverra porta lorem. Phasellus dignissim, mauris id vulputate malesuada, tortor metus placerat justo, bibendum vehicula velit magna in leo. Sed condimentum tortor ac ipsum ultricies, quis tristique massa malesuada. Vivamus vitae congue felis. Etiam dictum aliquet felis. Sed euismod in sem eu semper. Nam pulvinar nisl nisi, venenatis bibendum leo lobortis vel.<\/p><p>Nulla pharetra odio non leo sollicitudin, vel semper lorem sagittis. Pellentesque viverra pulvinar elementum. Donec pulvinar consequat augue. Aenean vitae libero sit amet quam faucibus pulvinar ac sit amet nibh. Fusce venenatis magna nulla. Curabitur dignissim justo eu purus pharetra suscipit. Donec tempus eros eget cursus vestibulum.<\/p>",
    "footer": "Copyright &copy; 2019"
}

如何仅抓取This is me doing a test之后的文本"header":并使用HTML标记将其附加到我的h1上?

这是我下面的HTML

<h1></h1>

  <ul id="menu">
    <li></li>
    <li>
      <ul>
        <li></li>
        <li></li>
      </ul>
    </li>
    <li></li>
  </ul>

  <h2></h2>
  <p></p>

  <div id="footer">
    <p></p>
  </div>

我知道我可以手动键入所有数据,但是我需要通过.txt文件导入。

1 个答案:

答案 0 :(得分:1)

是的,您可以使用JSON.stringifyJSON.parse

$.get('assets/test.txt', function(data) {
    var obj = JSON.parse(data);
    var headerText = obj["header"];
    $("h1").text(headerText);
});