如何使用jquery或java脚本从URL(Rest API)获取JSON数据到UI

我有一个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,这对我不起作用这是我的代码如果代码错误请纠正我。

     $.getJSON('/api/rest/abc', function(data) { console.log(data); });      

在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); }); });