Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问JavaScript中的json字符串_Javascript_Java_Json_Servlets_Arraylist - Fatal编程技术网

访问JavaScript中的json字符串

访问JavaScript中的json字符串,javascript,java,json,servlets,arraylist,Javascript,Java,Json,Servlets,Arraylist,我有一个名为json的字符串,它有ArrayList值。我使用Gson将arraylist转换为json。我将json作为POST中的响应从servlet传递给javascript 我在js中得到的响应是[“1.343”、“73.6544”、“32.6454”、“34.453”、“43.565”、“23.454”]。如何使用变量单独访问js中的这些值(这些是位置坐标)。我想使用这些值来显示地图中的位置 如何在js中访问这些值。在js中获得的值是一个包含arraylist的字符串。我使用gson转

我有一个名为json的
字符串,它有
ArrayList
值。我使用Gson将arraylist转换为json。我将json作为
POST
中的响应从servlet传递给javascript

我在js中得到的响应是
[“1.343”、“73.6544”、“32.6454”、“34.453”、“43.565”、“23.454”]
。如何使用变量单独访问js中的这些值(这些是位置坐标)。我想使用这些值来显示地图中的位置

如何在js中访问这些值。在js中获得的值是一个包含arraylist的字符串。我使用gson转换为字符串

这是js:

<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            data.toString();
            alert(data);
        }
    }
    xhr.open('POST', 'GetLocationFromDB', true);
    xhr.send(null);
</script>

解析对Json的响应,您就可以访问这些元素

var json = JSON.parse(data);
阅读更多关于JSON.parse的信息

作为对JSON.parse工作原理的简单测试

var x = JSON.parse('["1.343","73.6544","32.6454","34.453","43.565","23.454"]');
alert(x[0]) // alerts with 1.343 
这是你应该吃的

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        var json = JSON.parse(xhr.responseText);
        console.log(json); 
        //or if you like alerts
        alert(json);
    }
}
xhr.open('POST', 'GetLocationFromDB', true);
xhr.send();

您必须解析
数据


JSON.parse()
用于将JSON文本字符串解析为javascript对象,以及
JSON.stringify
用于将javascript对象图灵为JSON文本。

我尝试在
alert()
中显示解析后的变量,但没有出现警报。使用
console.log()
取而代之。我得到了
未捕获的语法错误:JSON输入意外结束
我试图在
alert()
中查看已解析的变量,但没有出现警报。我做了这个
警报(JSON.parse(data))
。我甚至尝试将
数据
转换为字符串和解析。没有工作那么你的数据是空的。它不是空的。在解析之前,我可以在警报中显示它。它在警报框中显示为
[“1.343”、“73.6544”、“32.6454”、“34.453”、“43.565”、“23.454”]
尝试{JSON.parse(data);}catch(error){alert(error);}
我得到了
未捕获的语法错误:JSON输入意外结束
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        var json = JSON.parse(xhr.responseText);
        console.log(json); 
        //or if you like alerts
        alert(json);
    }
}
xhr.open('POST', 'GetLocationFromDB', true);
xhr.send();