简体   繁体   中英

fetch data using jQuery from external JSON site, Singleton class

I am being trained and my task is to fetch data using jQuery from external JSON site. I am using a Singleton class to do so. The data will be fetched from this site during initialization and data will be added to the class as attributes. As a hint I was told to use the callback functionality to ensure that the data is being fetched. This link shows what I figured out so far. I run this script on html (loaded jquery) and I get no results. I am not sure if my jQuery code is correct.

Any kind of advice/guidance is greatly appreciated.

Thank you.

Your script is working, problem is that the alert is outside of the ajax success callback so you dont see it.

 jQuery.ajax({
            type: "GET",
            url: feedurl,
            dataType: 'json',
            data: 'data',
            success: function(data) {
                object = data;
            } 
        });     alert(object);

This should be :

 jQuery.ajax({
            type: "GET",
            url: feedurl,
            dataType: 'json',
            data: 'data',
            success: function(data) {
                object = data;
                    alert(object); 
            } 
        });  

For info, you can do the same thing with only :

$.getJSON('http://freegeoip.net/json/', function(data) {
  alert(data);
});

There are tons of examples of using jquery to access an api over http. One example would be:

$.getJSON( "ajax/test.json", function( data ) {
    var items = [];
    $.each( data, function( key, val ) {
        items.push( "<li id='" + key + "'>" + val + "</li>" );
    });
    $( "<ul/>", {
        "class": "my-new-list",
        html: items.join( "" )
    }).appendTo( "body" );
});

http://api.jquery.com/jQuery.getJSON/

What problem are you solving by using a Singleton? Why do you need to enforce a single instance of a class?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM