【问题标题】:Access json string in JavaScript在 JavaScript 中访问 json 字符串
【发布时间】:2023-04-06 22:41:02
【问题描述】:

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

我在 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>

data 是来自 servlet 的值。 SERvlet:

String json = new Gson().toJson(arraylist);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);

【问题讨论】:

    标签: javascript java json servlets arraylist


    【解决方案1】:

    解析对 Json 的响应,您将可以访问元素

    var json = JSON.parse(data);
    

    在此处阅读有关 JSON.parse 的更多信息。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/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();
    

    【讨论】:

    • 我试图在alert() 中查看已解析的变量,但没有出现警报。我做到了alert(JSON.parse(data))。我什至尝试将data 转换为字符串并进行解析。没用
    • 那么你的数据是空的。
    • 它不是空的。在解析之前,我可以在警报中显示它。它在警告框中显示为["1.343","73.6544","32.6454","34.453","43.565","23.454"]
    • try { JSON.parse(data); } catch(error) { alert(error); }
    • 我收到Uncaught SyntaxError: Unexpected end of JSON input
    【解决方案2】:

    你必须解析你的data

    JSON.parse() 用于将 JSON 文本字符串解析为 javascript 对象,JSON.stringify 用于将 Javascript 对象转换为 JSON 文本。

    【讨论】:

    • 我试图在alert() 中显示解析的变量,但没有出现警告。
    • 改用console.log()
    • 我收到Uncaught SyntaxError: Unexpected end of JSON input
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多