使用 Javascript 读取 URL 中显示的 JSON 字符串
Read JSON String Shown In URL Using Javascript
我正在尝试创建一个简单的网络应用程序,它获取存储在 JSON 字符串中的纬度和经度,并使用它们在 google 地图上放置标记。目前,我在服务器上有一个程序,当在 Web 浏览器中输入 URL 时,它会检索带有数据的 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对象,这是可以在之后完成的事情。
你可以使用
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"];
对普通字符串试试这个:
JSON.parse(str)
或者,如果您使用 AJAX 来获取 Json,您可以使用以下方法:
$.get(..,'json')
或
$.post(..,'json')
使用Jquery库的get方法从服务器请求数据。这是一个 link 到简单的 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
});
});
我正在尝试创建一个简单的网络应用程序,它获取存储在 JSON 字符串中的纬度和经度,并使用它们在 google 地图上放置标记。目前,我在服务器上有一个程序,当在 Web 浏览器中输入 URL 时,它会检索带有数据的 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对象,这是可以在之后完成的事情。
你可以使用
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"];
对普通字符串试试这个:
JSON.parse(str)
或者,如果您使用 AJAX 来获取 Json,您可以使用以下方法:
$.get(..,'json')
或
$.post(..,'json')
使用Jquery库的get方法从服务器请求数据。这是一个 link 到简单的 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
});
});