Jquery getJSON IP

I am trying to convert the following code to work with jquery:

var req = new XMLHttpRequest(); 
  req.open('GET', 'http://jsonip.appspot.com', true); 
  req.onreadystatechange = function (e) { 
    if (req.readyState === 4) { 
      if(req.status === 200) {
        var ip = JSON.parse(req.responseText);
        alert(ip.address);
      } else { 
        alert("Error loading page\n"); 
      }
    } 
  }; 
  req.send(null); 

      

This is the jquery part that doesn't work:

  $.getJSON("http://jsonip.appspot.com",
        function(data){
             alert( "Data Returned: " + data.ip);

        });

      

+2


source to share


2 answers


This host supports JSONP custom callbacks, so you can get the result:

 $.getJSON("http://jsonip.appspot.com?callback=?",
    function(data){
       alert( "Data Returned: " + data.ip);
  });

      



Check the above code here .

+7


source


Try the following:



$.getJSON('http://jsonip.appspot.com?callback=?', function(data) { 
    console.log( data.ip ); 
} );

      

+1


source







All Articles