简体   繁体   English

使用jQuery从Ajax调用访问键值对

[英]Accessing key value pairs from ajax call with jQuery

I am using jquery to call for a Json object from the server. 我正在使用jquery从服务器调用Json对象。 This is my call: 这是我的电话:

$.getJSON( url, function( data ) {...}

I am getting back (from console.log) the following object: 我从console.log返回以下对象:

> 0: Object
   cable key: "1"
   cable type: "Building Wire..."
> 1: Object
   cable key: "2"
   cable type: "PVC Wire..."
...

I am trying to access both key and value like the examples below without any luck. 我试图像下面的示例一样访问键和值,但没有任何运气。

$.getJSON( url, function( data ) {

    $.each( data, function( key,  value ) {

         $( "#CableType" ).append( $( "<option value='" + value['cable key'] + "'>" + value['cable type'] + "</option>" ) );

    });
})

Thanks for any help 谢谢你的帮助

You are trying to get a property of the VALUE instead of the object. 您正在尝试获取VALUE的属性而不是对象。 Use 采用

data['cable key']

instead of 代替

value['cable key']

Beside, adding elements to the DOM inside a loop is inefficient. 此外,在循环内将元素添加到DOM效率很低。 You need to collect your html in a string, and after the loop ends, put it in the DOM. 您需要将您的html收集为字符串,然后在循环结束后将其放入DOM中。 You can do something like this: 您可以执行以下操作:

$.getJSON( url, function(data){
    var htmlCollection = "",
        propertyName;

    data.forEach(function(pair){            
        htmlCollection += "<option value='" + pair['cable key'] + "'>" + pair['cable type'] + "</option>";
    });

    $( "#CableType" ).append(htmlCollection);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM