How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

后端 未结 4 2007
悲哀的现实
悲哀的现实 2021-02-04 08:26

I have a URL \"http://localhost:8888/api/rest/abc\" which will give following json data. I wants to get this data in my UI using Jquery or java script. I\'m trying

相关标签:
4条回答
  • 2021-02-04 09:00

    Send a ajax request to your server like this in your js and get your result in success function.

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

    at server side send response as json type.

    And you can use jQuery.getJSON for your application.

    0 讨论(0)
  • 2021-02-04 09:01
     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`
                        }
                    }
                });     
    
    0 讨论(0)
  • 2021-02-04 09:05

    You can use native JS so you don't have to rely on external libraries.

    (I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?

    fetch('/api/rest/abc')
        .then(response => response.json())
        .then(data => {
            // Do what you want with your data
        });
    

    You can also capture errors if any:

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

    By default it uses GET and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference

    0 讨论(0)
  • 2021-02-04 09:11

    You can use us jquery function getJson :

    $(function(){
        $.getJSON('/api/rest/abc', function(data) {
            console.log(data);
        });
    });
    
    0 讨论(0)
提交回复
热议问题