Retrieve a json final value in Javascript

6

Is it possible to retrieve a value from a result of a url by jQuery?

My problem is the following, I need to receive the final result of this url:

link

I need to retrieve this result through JavaScript.

    
asked by anonymous 20.02.2014 / 03:27

5 answers

10

Use $.getJSON :

$.getJSON(url, function (resultado){
  // use o resultado
});
    
20.02.2014 / 03:41
6

A variant without jQuery, inhaled here :

var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=-12.9945,-38.5266&sensor=false';
httpGet(url);

function httpGet(theUrl) {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var objectResposta = JSON.parse(xmlhttp.response);  // usando JSON.parse()
            console.log(objectResposta.results);                // log para a consola
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();
}

In the case of google maps this works because it allows requests from different domains, but in other cases it may not work because of the beginning of the same source and CORS (Cross-origin resource sharing / Sharing resources in different sources).

    
20.02.2014 / 09:06
1

As the colleague @Gustavo Rodrigues replied, the code below worked perfectly:

$.getJSON('http://maps.googleapis.com/maps/api/geocode/jsonlatlng=-12.9945,-38.5266&sensor=false', null, function (data) {
    alert(data.results[1].address_components[0].long_name); // Resultado: "Av. 7 de Setembro, S/N"
})

I tested on a simple html page and an ASP.NET MVC application.

    
26.02.2014 / 15:17
0

A good suggestion as well.

var ajax = function(url, requestType, callback, queryString) {
    var ids = ['MSXML2.XMLHTTP.3.0',
    'MSXML2.XMLHTTP',
    'Microsoft.XMLHTTP'],
    xhr;
    if (window.XMLHttpRequest)
      xhr = new XMLHttpRequest();
    else {
      for (var i = 0; i < ids.length; i++) {
        try {
          xhr = new ActiveXObject(ids[i]);
          break;
        } catch(e) {}
      }
    };
    xhr.onreadystatechange = function() {
        if(xhr.readyState== 4){
            if(xhr.status==200)
                 callback(xhr);          
        }        
    };
    xhr.open(requestType, url, true);
    if (requestType.toUpperCase() === 'GET')      
      xhr.send();
    else if (requestType.toUpperCase() === 'POST')
      xhr.send(queryString);      
};
ajax("http://maps.googleapis.com/maps/api/geocode/json?latlng=-12.9945,-38.5266&sensor=false","GET",function(xhr){
   var ResultJSON = JSON.parse(xhr.response);
   console.log(ResultJSON);
});
    
20.02.2014 / 14:32
0

Since you are using google maps to do this, one way to do that is to use the api that they provide.

Here's an example:

link

    
26.02.2014 / 21:26