使用Javascript读取URL中显示的JSON字符串

时间:2015-01-02 02:03:40

标签: javascript json

我正在尝试创建一个简单的网络应用,它可以获取存储在JSON字符串中的纬度和经度,并使用它们在谷歌地图上放置标记。目前,我在服务器上有一个程序,当URL被输入到Web浏览器中时,它会检索带有数据的JSON字符串。生成的JSON字符串如下: -

{"employees":[{"email":"bones93@hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}

我可以在JavaScript中使用哪种方法来获取生成的JSON字符串?

P.S我知道我之后需要解析文本来制作一个JSON对象,这可以在之后完成。

3 个答案:

答案 0 :(得分:1)

使用Jquery库的get方法从服务器请求数据。这是一个简单的W3教程的链接:http://www.w3schools.com/jquery/ajax_get.asp

您的代码将如下所示:

$("button").click(function(){
  $.get("/your/server/url",function(data){
    var result = JSON.parse(data);
    // Process result.employees
  });
});

答案 1 :(得分:0)

您可以使用

var x = JSON.parse('{"employees":[{"email":"bones93@hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}');

然后使用以下命令访问它:

x["employees"][0]["lat"];

答案 2 :(得分:0)

尝试使用普通字符串:

JSON.parse(str)

或者如果你使用AJAX来获取Json,你可以使用如下:

$.get(..,'json')

$.post(..,'json')