从javascript加载json时出错

Getting error trying to load json from javascript

本文关键字:出错 json 加载 javascript      更新时间:2023-09-26

我的javascript有一些问题。我试图加载json数组ag-grid像这样,下面的工作很好,因为我只是从json文件加载json:

    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', '../dist/output.json');
    httpRequest.send();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            var httpResult = JSON.parse(httpRequest.responseText);

            function isNumeric(n) { 
                return !isNaN(parseFloat(n)) && isFinite(n);
            }
            var parsedData = httpResult.map(function(obj) {
                return Object.keys(obj).reduce(function(memo, key) {
                    var value = obj[key];
                    memo[key] = isNumeric(value) ? Number(value) : value;
                    return memo;
                }, {})
            })

但是,当我以以下方式执行时(即,从jsp获取json数组),console.log(jsonArray)显示良好,但我得到错误:

var jsonArray = document.getElementById("jsonArray");
        console.log(jsonArray);
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', jsonArray);
        httpRequest.send();
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                var httpResult = JSON.parse(httpRequest.responseText);

                function isNumeric(n) { 
                    return !isNaN(parseFloat(n)) && isFinite(n);
                }
                var parsedData = httpResult.map(function(obj) {
                    return Object.keys(obj).reduce(function(memo, key) {
                        var value = obj[key];
                        memo[key] = isNumeric(value) ? Number(value) : value;
                        return memo;
                    }, {})
                })

我得到以下错误:

Failed to load resource: the server responded with a status of 404 (Not Found)

如何改变第一个代码,以便我可以正确地从jsonArray中读取,其中包含所有json数据。

更新:

jsonArray是jsp中的以下内容:

JSONArray jsonArray = new JSONArray(orderDetailsList1);
<input type="hidden" value="<%out.println(jsonArray);%>" id="jsonArray"/>

jsonArray是一个DOM对象。要访问它的value属性,使用value属性:

httpRequest.open('GET', jsonArray.value);