2011-10-11 55 views
3

我知道我的問題已經回答了很多次,但我仍然無法弄清楚如何爲我做一件事。 我現在想通過閱讀論壇來解決我的問題,但我可能在基礎知識上有些問題,我找不到,而且我需要您的幫助。我無法用getJson讀取JSON

我有一個創建一個JSON(至少我是這麼認爲的),這裏是代碼

 JSONObject json = new JSONObject(); 
    for(int i=0; i<20; i++){ 
     JSONObject jsonItem = new JSONObject(); 
     jsonItem.put("position", positions[i]); 
     json.accumulate("group", jsonItem); 
    } 

    String output = json.toString(); 

    response.setContentType("application/json");  
    PrintWriter out = response.getWriter(); 
    out.print(output); 
    out.flush(); 

一個servlet如果我跑我得到了以下這個servlet:

{ 
    "group": [ 
    { 
     "position": 235 
    }, 
    { 
     "position": 61 
    }, 
    { 
     "position": 248 
    }, 
    { 
     "position": 206 
    }, 
    { 
     "position": 26 
    }, 
    { 
     "position": 329 
    }, 
    { 
     "position": 176 
    }, 
    { 
     "position": 180 
    }, 
    { 
     "position": 218 
    }, 
    { 
     "position": 83 
    }, 
    { 
     "position": 177 
    }, 
    { 
     "position": 142 
    }, 
    { 
     "position": 17 
    }, 
    { 
     "position": 249 
    }, 
    { 
     "position": 310 
    }, 
    { 
     "position": 369 
    }, 
    { 
     "position": 251 
    }, 
    { 
     "position": 256 
    }, 
    { 
     "position": 337 
    }, 
    { 
     "position": 63 
    } 
    ] 
} 

我jQuery是如下:

$(document).ready(function(){ 
    $("#clickMe2").click(function(){ 
     alert("something2"); 
    $.getJSON("/RandomNumGen",function(result){ 
     alert("something3"); 
     $.each(result, function(i, field){ 
     $("#myTarget").append(field + " "); 
     }); 
    }); 
    }); 
}); 

也許這不是正確的方式來閱讀它,但它永遠不會去第二個提醒「something3」。所以我認爲它從不讀取JSON。 我嘗試了很多方法來閱讀它,但似乎問題是從來沒有讀取JSON。

我在tomcat 7.0.22上運行servlet,我有@WebServlet("/RandomNumGen"),我認爲這意味着我不需要web xml但沒有運行,所以我決定創建一個web.xml 。 奇怪的是,當我試着用MIME「text/html」返回一些東西,然後用普通文件得到$.get,它確實得到了它,並在瀏覽器上打印[Object object]

顯然我之前沒有使用過JSON,因爲我在教程中運行得非常快,所以我可能會錯過基本知識。

回答

2

你的jquery是錯誤的。你必須改變你的$.each。試試這個

$.each(result.group, function(i, field){ 
    $("#myTarget").append(field.position + " "); 
}); 

檢查了這一點 http://jsfiddle.net/xV2vx/

+0

謝謝你的修正,更多的是介紹我jsfiddle.net!然而,我不認爲我的錯誤的「每個」是沒有正確運行「alert('something3')」的原因...... –