Javascript 如何在另一个页面中获取json数据?
我想查看每个用户到其他页面。 如何使用ajax获取用户json数据Javascript 如何在另一个页面中获取json数据?,javascript,json,ajax,Javascript,Json,Ajax,我想查看每个用户到其他页面。 如何使用ajax获取用户json数据 "users": [ { { "id": "01", "name": "Joseph", "age": "20", }, { "id": "02", "name": "Christ", "age": "20" } }] <a href="view.html?id=01"> View J
"users": [
{
{
"id": "01",
"name": "Joseph",
"age": "20",
},
{
"id": "02",
"name": "Christ",
"age": "20"
}
}]
<a href="view.html?id=01"> View Josepth </a>
<a href="view.html?id=02"> View Christ </a>
“用户”:[
{
{
“id”:“01”,
“姓名”:“约瑟夫”,
“年龄”:“20岁”,
},
{
“id”:“02”,
“名字”:“基督”,
“年龄”:“20”
}
}]
因此,首先您可以从URL获取用户id(您可以使用),然后根据服务器公开端点的方式,使用window.prototype.fetch
()调用它,如下所示:
(异步函数(){
常量url=新url(“http://view.html?id=02");
const{searchParams}=url;
const userId=searchParams.get(“id”);
const userData=等待获取(`https://yourapi.com/user/${userId}`);
console.log(userData);
})()
希望有帮助,请注意,由于您没有向我提供有关如何请求此数据的信息(提供数据的服务器如何公开其数据-其API),我猜想您发送了一个GET
,用户id作为查询参数
因为您已经在上面告诉我您有一个data.json
,所以您只需要从URL获取用户id,然后像这样过滤解析后的json:
const data = JSON.parse(require('./data.json'));
const url = new URL("http://view.html?id=02");
const { searchParams } = url;
const userId = searchParams.get("id");
const userData = data.filter((user) => user.id === userId);
// here you should see the object with the data for that specific user Id
console.log(userData);
需要更多信息,您从哪里获取数据?它是用脚本硬编码的吗?这取决于你想从服务中获取它的URL中的id吗?取决于URL,我看到了它,但只有一页我有索引文件、视图文件和数据。我不知道我是否正确理解你的问题,但如果你已经在
data.json
中获得了所需的数据,我看不到使用ajax的必要性。