[英]reading json using jquery
I have following json 我有以下json
[{\"Country\":\"Europe\",\"City\":[\"Berlin\",\"Istanbul\",\"London\",\"Manchester\",\"Milan\",\"Paris\"]},null]
I want to read the country and its cities. 我想读这个国家及其城市。
I have tried it like this 我已经尝试过了
var eu = jQuery.parseJSON($("#EU").val());
for( i=0; i<eu.length();i++)
{
alert( eu[0][0]);
}
But I am getting undefined error in alert. 但是我在警报中收到未定义的错误。
How can I accomplish the above task? 如何完成上述任务?
length
is a property and not a method. length
是属性而不是方法。 Just drop the ()
: 只需删除
()
:
for( i=0; i<eu.length;i++) {
alert( eu[i].Country );
}
Furthermore, you have an Array of objects, so eu[0][0]
does not exists. 此外,您有一个对象数组,因此
eu[0][0]
不存在。 To output the country, eg., use eu[0].Country
or eu[0]['Country']
. 要输出国家,例如,使用
eu[0].Country
或eu[0]['Country']
。
Besides, your second Array element is null, so you should check for that (or receive an error): 此外,您的第二个Array元素为null,因此您应该检查一下(或收到错误):
for( i=0; i<eu.length;i++) {
if( 'Country' in eu[i] ) {
alert( eu[i].Country );
}
}
You can try this within the for
loop : 您可以在
for
循环中尝试:
for( i=0; i<eu.length;i++)
{
alert( eu[0]['Country']);
alert( eu[0]['City'][0]);
}
if #EU
is an form input
it will get the json, if its a div
or html element try text()
to get the json 如果
#EU
是form input
则它将获取json,如果其div
或html元素尝试使用text()
获取json
$("#EU").text();
and the fix the loop 并修复循环
for( var i=0, x = eu.length; i < x; i++) //length
You can use below code which is much simpler. 您可以使用以下更简单的代码。
var vJson = [{"Country":"Europe","City":["Berlin","Istanbul","London","Manchester","Milan","Paris"]}];
$.each(vJson, function(idx, obj) {
alert(obj.Country); // Get Country
$.each(obj.City, function(idx1, obj1) {
alert(obj1); // Get multiple city of country
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.