2014-02-21 44 views
0

從服務器響應我得到:與格式JSON數組問題

{"vorname":["muss ausgefüllt werden"],"name":["muss ausgefüllt werden"]} 

所以我做這個JSON數組xhr.responseText是這樣的:

$.each(jQuery.parseJSON(xhr.responseText), function(i, val) { 
      console.log(val[0]); 
    }); 

通常我會想到這個輸出:

vorname  
name 

,但我得到:

muss ausgefüllt werden 
muss ausgefüllt werden 

爲什麼?我該如何解決它?謝謝

+0

你需要的是'i'不'val' – Spokey

回答

1

爲什麼?我該如何解決它?

jQuery.parseJSON(xhr.responseText)結果是對象$.each傳遞名稱的屬性作爲第一個參數的,其作爲第二個參數回調。

看來你要記錄的名字,所以你必須登錄i,不是值val

$.each(jQuery.parseJSON(xhr.responseText), function(i, val) { 
    console.log(i); 
}); 

documentation的例子是不言自明IMO:

如果使用對象作爲集合,則回調每次都會通過一個 鍵值對:

var obj = { 
    "flammable": "inflammable", 
    "duh": "no duh" 
}; 
$.each(obj, function(key, value) { 
    alert(key + ": " + value); 
}); 

再次,這將產生兩個信息:

flammable: inflammable 
duh: no duh 
2

如果你只想得到key財產的名稱。我建議你用簡單for-in loop

for (var item in jQuery.parseJSON(xhr.responseText)) { 
    console.log(item) 
} 

編輯

目前正在打印哪裏,你需要獲得的財產keyvalue。所以你應該打印key每個回調的第一個參數。所以你可以使用。

$.each(data, function(key, val) { 
    console.log(key); 
}); 

DEMO with JSON data including both for-in and $.each

+0

這無疑提供了一個解決方案,它並不能說明問題。 –

+0

@FelixKling,對不起,我懶惰不提供解釋。我認爲代碼是自我解釋的,因此跳過了那個 – Satpal

1

試試這個:

$.each(jQuery.parseJSON(xhr.responseText), function (key, val) { 
    console.log(key); 
}); 

你必須返回keyJSON對象的,按照文檔$.each()

如果對象被用作集合(在您的案例中也是),每次都會傳遞一個鍵值對。

var obj = { 
    "flammable": "inflammable", 
    "duh": "no duh" 
}; 
$.each(obj, function(key, value) { // key returns key of json object. 
    alert(key + ": " + value); // alert(flammable: inflammable); 
});        //----------^^key^^----^^-value-^^-- 

此提醒兩倍

flammable: inflammable // alert(flammable: inflammable); 
duh : no duh    //--^^key^^----^^-value-^^-- 

其中在警報:前項是在JSON對象密鑰和另一個是相應值。

+0

爲什麼OP應該這樣做?你能否提供**解釋**? –

+0

@FelixKling我在寫這篇文章。 – Jai

0

因爲您正在打印VAL而不是KEY。 難道你有什麼期望:

$.each(jQuery.parseJSON(xhr.responseText), function(key , val) { 
     console.log(key); 
}); 

Here a demo

說明: 如果你看一看JQuery API

「[..] $。每()函數可用於任何集合遍歷,無論是一個對象或數組[ ..該方法返回第一個參數,這是迭代的對象[..]「

1

嘗試:

var obj = jQuery.parseJSON(yourResponse) 
for (var key in obj){ 
    console.log(key + ':' + obj[key]) 
} 

響應:

vorname:搞亂ausgefülltwerden 名稱:搞亂ausgefülltwerden