Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Json Array with pure JS

I would like to get JSON Array from a cross domain without using JQuery. The data from cross domain is like this:

{
      "transactionid": "LBS_48550801",
      "status": 0,
      "countrylist": 
    [
   { "id": 1, "name": "France", "latitude": 37.00039, "longitude": 35.31411, "extent": { "minlatitude": 36.53888499, "minlongitude": 34.76786904, "maxlatitude": 38.37851496, "maxlongitude": 36.40534884 }},
   { "id": 2, "name": "Germany", "latitude": 37.76454, "longitude": 38.27645, "extent": { "minlatitude": 37.40771898, "minlongitude": 37.43326512, "maxlatitude": 38.21203404, "maxlongitude": 39.24767592 } },
   //... .... .... 
   //... .... .... 
   //... .... .... 
   { "id": 98, "name": "Belgium", "latitude": 38.75754, "longitude": 30.5387, "extent": { "minlatitude": 37.78126803, "minlongitude": 29.68963308, "maxlatitude": 39.27915099, "maxlongitude": 31.71549708 } },
   { "id": 99, "name": "England", "latitude": 39.71812, "longitude": 43.03345, "extent": { "minlatitude": 38.96877501, "minlongitude": 42.28340184, "maxlatitude": 40.031208, "maxlongitude": 44.61092892 } },
    ]
}

After getting the data, I need to parse it to get "countrylist" list.

I searched for solving this issue but the examples are all with JQuery. I dont want to use it. As you see, I have transactionid, status parameters in the input. So, after importing the data, I need to parse it to get the countrylist array. I know how to parse it, but I couldnt get the whole data from the service.

I need to get the data by Javascript methods. The server supports retrieving data well.

The steps to be taken are:

1- Get the whole data (Here is where I got stuck)

2- Parse it as Json Object (I know how to parse the data)

How can I get the whole data without using any JQuery or other prepared libraries?

like image 246
Mark Karan Avatar asked Dec 23 '13 12:12

Mark Karan


2 Answers

You can use XMLHttpRequest for ajax and JSON.parse for parse json :)

var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '//example.org', true);
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
        if(xmlhttp.status == 200) {
            var obj = JSON.parse(xmlhttp.responseText);
            var countryList = obj.countrylist;
         }
    }
};
xmlhttp.send(null);

You should never use eval! Eval is evil! You can read about it on mdn

UPD:

If there is no CORS header, you can use JSONP. Just add &callback=getJSONP to your URL. Try it on jsfiddle: http://jsfiddle.net/VmBF7/3/

like image 130
kmakarychev Avatar answered Oct 19 '22 17:10

kmakarychev


since your operation involving cross domain requests, i suggest you to use jsonp request.

this question has what you wanted.

like image 1
denolk Avatar answered Oct 19 '22 19:10

denolk