![](/img/trans.png)
[英]Read data from JSON Url using plain javascript and display it in HTML
[英]How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?
我有一个 URL“ http://localhost:8888/api/rest/abc
”,它将提供以下 json 数据。 我想使用 Jquery 或 java 脚本在我的 UI 中获取这些数据。 我从几个小时开始尝试这个,但我无法解决它。 请建议我一些解决方案,这将帮助我解决这个问题。
{
"My-user": [
{
"link": [
{
"href": "http://localhost:8888/api/rest/abc/MI/CH",
"rel": "self",
"type": "application/my.My.My-user+xml",
"title": "rln"
},
{
"href": "http://localhost:8888/api/rest/cabin?MI=mi&CH=ch",
"rel": "some relation",
"type": "application/my.My.My-cabin+xml",
"title": "rln1"
}
],
"My-user-list": [
{
"name": "cuba",
"Explanation": "bark"
}
],
"CH": "ch",
"MI": "mi",
"password": "xyz",
},
{
"link": [
{
"href": "http://localhost:8888/api/rest/abc/DD/KN",
"rel": "self",
"type": "application/my.My.My-user+xml",
"title": "rln"
},
{
"href": "http://localhost:8888/api/rest/cabin?DD=dd&KN=kn",
"rel": "some relation",
"type": "application/my.My.My-cabin+xml",
"title": "rln1"
}
],
"My-user-list": [
{
"name": "Cuba1",
"Explanation": "bark1"
}
],
"KN": "kn",
"DD": "dd",
"password": "xyz1",
}
]
}
我试过 Getjson 对我不起作用 这是我下面的代码 如果代码错误,请纠正我。
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$.getJSON('/api/rest/abc', function(data) {
console.log(data);
});
</script>
</head>
<body>
</body>
</html>
像这样在你的 js 中向你的服务器发送一个 ajax 请求,并在成功函数中获得你的结果。
jQuery.ajax({
url: "/rest/abc",
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
//here is your json.
// process it
},
error : function(jqXHR, textStatus, errorThrown) {
},
timeout: 120000,
});
在服务器端以 json 类型发送响应。
您可以将jQuery.getJSON用于您的应用程序。
您可以使用原生 JS,因此您不必依赖外部库。
(我将使用一些 ES2015 语法,又名 ES6,现代 javascript)什么是 ES2015?
fetch('/api/rest/abc')
.then(response => response.json())
.then(data => {
// Do what you want with your data
});
您还可以捕获错误(如果有):
fetch('/api/rest/abc')
.then(response => response.json())
.then(data => {
// Do what you want with your data
})
.catch(err => {
console.error('An error ocurred', err);
});
默认情况下,它使用GET
并且您不必指定标头,但是如果您愿意,您可以执行所有这些操作。 进一步参考: 获取 API 参考
您可以使用我们的 jquery 函数getJson :
$(function(){
$.getJSON('/api/rest/abc', function(data) {
console.log(data);
});
});
jquery.ajax({
url: `//your api url`
type: "GET",
dataType: "json",
success: function(data) {
jQuery.each(data, function(index, value) {
console.log(data);
`All you API data is here`
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.