java - 如何在 JavaScript 中访问 JSON 数组的元素?

标签 java javascript json jsp

我目前正在 Java 中创建一个 ArrayList,然后在其上运行来自 Google-gson 的 .toJson 函数:

public String statusesToJson(ArrayList<String> statuses){
    Gson gson = new Gson();
    return gson.toJson(statuses);
}

JSON 中的结果:

[ "u", "u", "u", "u" ]

然后在 JSP 中我将其传递给 JavaScript:

<script language="JavaScript" type="text/javascript">CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', '<%=model.arrayListToJson(model.getStatuses()) %>');</script>

然后在 JavaScript 中我将其解析为 JSON 数组:

CheckStatus.statuses = JSON.parse(statuses);
alert(CheckStatus.statuses);

这会产生以下输出:

u, u, u, u

问题是以下内容不起作用并导致我的页面无法加载:

alert(CheckStatus.statuses[0]);

这有什么问题吗?

编辑: 加载的函数:

loaded : function(guid, context, statuses) {
        CheckStatus.guid = guid;
        CheckStatus.context = context;
        CheckStatus.statuses = JSON.parse(statuses);
        alert(CheckStatus.statuses[0]);

        if(CheckStatus.init == null){
            submitForm('checkStatusForm', CheckStatus.guid);
            CheckStatus.init = true;
        }

        setupForm('checkStatusForm', function(){CheckStatus.validStatus();});

        //CheckStatus.setImages();

        applyCSS3('Check_Status');
    }

有效状态函数:

validStatus : function(){
        CheckStatus.params = $('#checkStatusForm').serializeObject();

        if(document.getElementById('regionID').value != "" && document.getElementById('regionAction').value != ""){
            submitForm('checkStatusForm', CheckStatus.guid);
        }else{
            error("Cannot Commit", "You must select an action before attempting to commit.");
        }
    },

设置表单功能:

/**
 * Sets up the form to submit when the user presses enter inside an input
 * element. Also calls the callback when the form is submitted, does not
 * actually submit the form.
 * 
 * @param id The id of the form.
 * @param callback The callback to call.
 * @return Nothing.
 */
function setupForm(id, callback) {
    $('#' + id + ' input').keydown(function(e) {
        if (e.keyCode === 13) {
            $(this).parents('form').submit();
            e.preventDefault();
        }
    });
    $('#' + id).submit(function(e) {
        e.preventDefault();
        callback();
    });
}

提交表单功能:

/**
 * Serializes and submits a form.
 * 
 * @param id
 *            The id of the form to submit.
 * @param guid
 *            The guid of the page the form is on to pass to the server.
 * @return nothing.
 */
function submitForm(id, guid) {
    var subTabId = $('#' + id).closest('#tabs > div > div').attr(
            'id'), tabId = $('#' + id).closest('#tabs > div')
            .attr('id'), data = $('#' + id).serializeArray();
    data.push( {
        name : "framework-guid",
        value : guid
    });
    $.ajax( {
        type : 'POST',
        cache : 'false',
        url : '/pasdash-web/' + tr("_", "", tabId.toLowerCase()) + '/' + tr("_", "", subTabId)
                + '.jsp',
        data : data,
        success : function(html) {
            $('#' + subTabId).html(html);
            resourceChanged(tabId, subTabId,
                    $('#' + id + ' input[name="framework_command"]')[0].value,
                    guid);
        },
        error : function(jqXHR, textStatus, errorThrown) {
            error('Ajax Error', textStatus);
        }
    });
    return false;
}

最佳答案

您不需要用字符串包装 JSON,这只会迫使您必须重新解析它。我会尝试删除这些引号而不调用 JSON.parse

loaded : function(guid, context, statuses) {
    CheckStatus.guid = guid;
    CheckStatus.context = context;
    // Here's the change
    CheckStatus.statuses = statuses;
    alert(CheckStatus.statuses[0]);

并将您的 HTML 更改为

<script type="text/javascript">
    CheckStatus.loaded('<%=model.getPageId() %>', 
                       '<%=request.getContextPath() %>',
                       // the following line should output something like
                       // ["a", "b"]
                       // which is perfectly valid JavaScript
                       <%=model.arrayListToJson(model.getStatuses()) %>);
</script>

关于java - 如何在 JavaScript 中访问 JSON 数组的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10904663/

相关文章:

java - 为什么 JSON 存储这样的对象 {"city":[ {"com.getcity.@FAE87A"}]}

javascript - 单击我网站上的任何链接 (a) 时如何运行 jQuery 函数

php - slim 的 JSON 输出

javascript - 为用户创建仪表板 - 我的方法需要帮助

javascript - momentjs toDate() - 时区被重置

java - Gson - 将多个 JSONs 对象合并为一个 JSON

javascript - 尝试从公共(public) API 解析 JSON 响应数据

java - JBox-2d 中的 'f' 有何用途?

java - 在不使用 sql 或 nosql 服务器的情况下将数据提供程序集成到应用程序

java - Elasticsearch : find all mapping types of a given index using the Java client