2012-06-05 100 views
1

我目前正在創建Java中的ArrayList中,然後運行從谷歌,GSON的.toJson功能就可以了:如何在JavaScript中訪問JSON數組的元素?

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; 
} 
+3

「我這來解析JSON數組」 - >不,你不是,你」將其從JSON數組解析爲JavaScript數組。 –

+0

這個「加載」函數到底做了什麼?你很可能沒有理由必須將JSON表示爲一個字符串;這是多餘的。 – Pointy

+0

嗯....不是JSON應該是名稱:值對?這看起來像一個普通的舊JS陣列。 –

回答

1

你不需要用字符串包裝你的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> 
+0

我想我已經嘗試了一次,頁面仍然凍結。當我早上回去工作時,我會再試一次,看看它不起作用時給出的控制檯輸出。 – PseudoPsyche

+0

好的,所以最初沒有用,正如我第一次嘗試它時所回憶的那樣。然而,現在我知道瀏覽器控制檯,我檢查了輸出,並看到數組在初始頁面加載時爲空。我只是在if語句中拋出一個if語句,看看它是否爲null,然後再做任何事情,它就完美了! – PseudoPsyche

0

你應該能夠編寫:

CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', <%=model.arrayListToJson(model.getStatuses()) %>); 

不帶引號周圍的最後一個參數。然後,該「loaded()」函數將直接獲取對象,並且不需要調用「JSON.parse()」。

+1

此外,它讓我非常難過在2012年看到JSP中的scriptlet。 – Pointy

+0

刪除引號和JSON。 parse(),然後調用alert(CheckStatus.statuses [0]);'仍然會導致頁面不加載。 – PseudoPsyche

+0

嘗試刪除引號但保留解析 – JohnB

0

檢查JSON.parse()的結果類型。在我看來,這是一個字符串,而不是一個數組。也許一對不應該在那裏的引號?