2016-01-25 19 views
2

我有以下Ajax調用的控制器方法如何檢索java設置並迭代Ajax調用的響應值?

$.ajax({ 
    type: "GET", 
    url: "../targeturl", 
    data : postdata, 
    contentType: 'application/json', 
    success: function(response, status, request) { 
    ** in response im getting three sets which i wish to iterate 
    } 

最後幾行如下:

JsonWrapper response = new JsonWrapper(); 
/*some lines to fetch data from db*/ 
response.addParam("vSet",vSet); 
response.addParam("dSet",dSet); 

return response; 

因爲我從來沒有試過,請告訴我知道如何執行此操作。如果問題不夠清楚,也請告知我。

+2

請提供控制器的正確的代碼。你使用了一些框架還是普通的servlet? –

+0

JSON響應如何? –

+0

@Luiggi,即時通訊使用spring mvc.method返回JsonWrapper的obj。 –

回答

1

使用JQuery的

$.each(response.vSet, function(index, element) { 
    //process 
}); 

使用的Javascript

for(var i=0;i<response.vSet.length;i++){ 
    //process 
} 
+0

它應該是'response.vSet.length'而不是'response.data.vSet.length' –

+1

第二個人在完成上述變更後爲我工作。 –

+0

對不起,這是一個錯字..我更新了答案:) –

1

如果您的回覆是有效的Json,您可以使用函數JSON.parse()中構建的javascript來解析迴應。然後按照你的喜好迭代它,這取決於你在響應中如何構建你的json。

$.ajax({ 
    type: "GET", 
    url: "../targeturl", 
    data : postdata, 
    contentType: 'application/json', 
    success: function(response, status, request) { 
     var json = JSON.parse(response). 
     //iterate over json by accessing the indices of json. 
     for(var i = 0; i < json.length; i++) 
     { 
      (..) //do stuff with json[i] 
     } 
     //or access json using the key values you specified in your response 
     json['vSet'] // or json.vSet. 

     console.log(json) //this will allow you to inspect your response after you parsed it to json. 
    } 
+0

我認爲在for循環中它應該是'var'而不是'int'。 –

+0

是的。如果我們使用你的解決方案,並且響應在我的情況下有多個集合,它就會變得更加複雜,如果我們將它編輯爲形式 – Glubus

+0

。 –