Retrieve a final value from a json in Javascript

Asked

Viewed 1,876 times

6

  • None of the answers answers your question?

5 answers

10

Use the $.getJSON:

$.getJSON(url, function (resultado){
  // use o resultado
});
  • It won’t work, it’s cross-Omain.

  • 4

    Use j s o n p o u Cors: the url returns Access-Control-Allow-Origin: * in the header.

  • 1

    Actually, released CORS: http://jsfiddle.net/jGp8N/

  • 1

    It’s a Google Maps API. If it wasn’t released it would make people lose themselves. Literally.

7


A variant without jQuery, infused 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 principle of the same origin and CORS (Cross-origin Resource sharing / Sharing resources from different backgrounds).

  • Ctrl+C Ctrl+V addicts: Ajax is IE5+, while JSON.parse is IE8+. It seems that everyone has forgotten this.

  • @Gustavorodrigues, truth :P edited...

1

Just as our colleague @Gustavo Rodrigues answered, 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 it on a simple html page and on an ASP.NET MVC application.

0

A good suggestion too.

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

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.