Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Json in Javascript variable

I'm studying javascript these days and I have question. I have variable that contain an url. I would like to save the content of the url pointed by my variable in another variable...

The first variable is something like:

var Link = "http://mysite.com/json/public/search?q=variabile&k=&e=1";

If I open the link I see something like:

{

"count": 1,
"e": 1,
"k": null,
"privateresult": 0,
"q": "gabriel",
"start": 0,
"cards": [
    {
        "__guid__": "cdf8ee96538c3811a6a118c72365a9ec",
        "company": false,
        "__title__": "Gabriel Butoeru",
        "__class__": "entity",
        "services": false,
        "__own__": false,
        "vanity_urls": [
            "gabriel-butoeru"
        ]
    }
]
}

How can I save the json content in another javascript variable?

like image 393
user1453638 Avatar asked Jun 20 '12 09:06

user1453638


People also ask

Can you use JSON in JavaScript?

JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.


1 Answers

You would need a simple AJAX request to get the contents into a variable.

var xhReq = new XMLHttpRequest();
xhReq.open("GET", yourUrl, false);
xhReq.send(null);
var jsonObject = JSON.parse(xhReq.responseText);

Please note that AJAX is bound by same-origin-policy, in case that URL is different this will fail.

like image 138
UltraInstinct Avatar answered Sep 29 '22 13:09

UltraInstinct