[英]How do i get data from json based on which ul li id is clicked?
This is my first project for website, but i decide to ask this, because i am not sure how to begin, despite watching countless of tutorials. 这是我的第一个网站项目,但是我决定问这个问题,因为尽管看了无数教程,但我不确定如何开始。
I have ul list items like this 我有ul这样的清单项目
<li><a href="posts.html?id=1">Data for id 1</a></li>
<li><a href="posts.html?id=2">Data for id 2</a></li>
And json.file like this 和json.file这样的
{
"posts": [{
"id": 1,
"postId": 1,
"img":"",
"title": ""
}]
}
I want this json to be filled with lots of objects and i want to get this by postId 我希望这个JSON充满很多对象,并且我想通过postId来获取它
I have no idea how to id.Everything i find is with Angular/React and i am still learning basic JS/Ajax 我不知道如何id。我发现的一切都是Angular / React,我仍然在学习基本的JS / Ajax
So, if i click li with ?id=1...to get all json data with "postId" 因此,如果我用?id = 1 ...单击li来获取带有“ postId”的所有json数据
That question is pretty broad, but maybe this will help you get started. 这个问题很广泛,但这也许可以帮助您入门。
It would be easier if you change your HTML structure slightly: 如果稍微更改HTML结构,会更容易:
<li><a href="" data-id="1">Data for id 1</a></li>
<li><a href="" data-id="2">Data for id 2</a></li>
Then you can add a bit of JS to add a click handler. 然后,您可以添加一些JS以添加单击处理程序。 I'm going to use jQuery here, but you can just as easily do this with pure JS, React, Angular, or whatever your heart desires.
我将在这里使用jQuery,但是您可以使用纯JS,React,Angular或任何您想要的东西轻松地做到这一点。
$('a').on('click', function(ev) {
ev.preventDefault();
$.get('/posts.php', {id: $(this).data('id')}).then(res => {
console.log(res);
});
});
Basically, we're adding a click handler to all <a>
s on the page (you should use a class to be more specific), and then firing off an ajax request , passing along the id
which we read out of data-id
. 基本上,我们要添加一个单击处理所有
<a>
在页面上S(你应该使用一个类更具体的),然后发射了一个Ajax请求 ,沿途经过的id
,我们读出的data-id
。
Now on the server you're going to have to write a script that parses your JSON file and returns the data you're interested in. I'll give you a bit of PHP to get you started, but you can do this with Node.js or any other server-side language: 现在,在服务器上,您将必须编写一个脚本来解析您的JSON文件并返回您感兴趣的数据。我将为您提供一些PHP入门,但是您可以使用Node来做到这一点。 .js或任何其他服务器端语言:
$json = json_decode(file_get_contents('yourfile.json'));
foreach($json['posts'] as $post) {
if($post['id'] == $_GET['id']) {
echo json_encode($post);
exit;
}
}
And then you have to decide what you actually want to do with that data after you've fetched it. 然后,在获取数据之后,您必须决定要对该数据执行的实际操作。 Here I've just logged it to Chrome/Firefox DevTool's console, but you'll probably want to display it to the user somehow.
在这里,我刚刚将其记录到Chrome / Firefox DevTool的控制台中,但是您可能希望以某种方式将其显示给用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.