我正在尝试从.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 © 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文件导入。
最佳答案
是的,您可以使用JSON.stringify
和JSON.parse
:
$.get('assets/test.txt', function(data) {
var obj = JSON.parse(data);
var headerText = obj["header"];
$("h1").text(headerText);
});
关于javascript - jQuery读取.text文件但获取特定数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54614709/