如何将服务器中的JSON数据转换为javascript变量

时间:2014-10-26 18:14:24

标签: javascript html

一些如此微不足道的东西,我似乎无法找到答案。 到目前为止这是我的代码。然而,这是将JSON alredy设置为变量。 我需要它以便从

获取JSON文本
 http://localhost:3001/sync/

并使其等于var txt。 var txt的INSTEAD =我想要它,所以从我添加的文本的URL INSTEAD中获取JSON文本。

 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;

2 个答案:

答案 0 :(得分:0)

看起来您需要使用xmlhttprequest(即.ajax)。它用于异步地从URL检索数据。

您可以关注a tutorial了解如何使用它。或者你可以学习如何使用jquery(特别是jquery.get)。

我建议如果你也不知道,你要么开始学习xmlhttprequest,要么最后还是使用jquery。

正如另一篇文章提到的,一旦你学会了如何检索数据,使用JSON.parse将文本解析为json,即使jquery也能自动处理它。

答案 1 :(得分:0)

据我了解,您希望数据来自URL并分配给变量txt。 在这种情况下,您需要使用jquery进行这样的ajax调用。

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

U现在可以使用JSON.parse(txt)来解析json。

相关问题