简体   繁体   中英

How do I get JSON data from a server into a javascript variable

Something so trivial and I just can't seem to find an answer. This is my code so far. However this is with the JSON alredy set as a variable. I need it so that it gets the JSON text from

 http://localhost:3001/sync/

and makes it equal to var txt. INSTEAD of the var txt = I want it so get the JSON text from the URL INSTEAD of the text I've added.

 var txt = '{"loading":false,"playing":true,"position":0,"duration":389492,"index":13,"repeat":false,"shuffle":false,"volume":0.337499052286148,"context":{"uri":"spotify:user:@:playlist:66HXOPaG8wwe7k8t4YZj5b"},"contexts":[{"index":13,"descriptor":{"type":"list","uri":"spotify:user:@:playlist:66HXOPaG8wwe7k8t4YZj5b"}}],"track":{"artists":[{"image":"spotify:image:15a09a886f2149909821763f2f074cf1b7975574","images":[[64,"spotify:image:1aa2b5417668fdfc6966c9745b437e587d7ff23f"],[300,"spotify:image:15a09a886f2149909821763f2f074cf1b7975574"],[600,"spotify:image:865b8c83601ce2aef204a9c071fd2f531c12c000"],[1000,"spotify:image:5311029c2ba3de0b4e5d117b4e90d57b60720902"]],"name":"Duke Dumont","uri":"spotify:artist:61lyPtntblHJvA7FMMhi7E"}],"disc":1,"duration":389000,"image":"spotify:image:6f592ef177e159c00dd4f08049c4c962466b0776","images":[[64,"spotify:image:68fd12e77d374e7b9618ca0cf6786b9479837175"],[300,"spotify:image:6f592ef177e159c00dd4f08049c4c962466b0776"],[600,"spotify:image:6a30d6808f92167b4cb10eed2cf5f9838442d591"]],"name":"The Giver - Original Mix","number":2,"playable":true,"popularity":64,"starred":false,"explicit":false,"availability":"premium","album":{"uri":"spotify:album:66Io82H9e3b2rrtHFs2sE0"},"local":false,"advertisement":false,"placeholder":false,"uri":"spotify:track:6GbLDdBuFxZLDHhluGrrmA"}}';

 var obj = eval ("(" + txt + ")");

 document.getElementById("demo").innerHTML =
 obj.playing;

It looks like you need to do use xmlhttprequest (ie. ajax). It is used to retrieve data from urls asynchronously.

You can either follow a tutorial to learn how to use it. Or you could learn how to use jquery (specifically jquery.get).

I'd suggest that if you don't know either, you either way start learning about xmlhttprequest but end up using jquery anyway.

And as the other post mentioned, once you learn how to retrieve data, use JSON.parse to parse the text to json, even though jquery can handle that automatically, too.

As far as I understand, u want the data to come from the URL and get assigned to variable txt. In tat case you need to make a ajax call like this using jquery.

$.ajax({
    url:"http://localhost:3001/sync/",
    success:function(result){
        var txt = result;
}});

U can now use JSON.parse(txt) to parse the json.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM