【问题标题】:Loop through json object and catch variables on the fly (jquery)循环遍历 json 对象并动态捕获变量(jquery)
【发布时间】:2010-07-15 03:44:31
【问题描述】:

使用 jQuery,我得到从数据库中提取一行的 JSON 对象。该行大约有 30 列,因此与行数据一起,成功消息 (success = true) JSON 结果返回带有名为 table_columns 的表列(例如:id、名称、地址等)的数组。

目的是将所有返回的数据放入相关的html表单字段中(例如:地址输入将用data.adress填充),我想发现让循环遍历data.table_columns数组并存储的技巧json 数据到其相应的表单输入中。让我给你看一个代码来更好地解释它:

$.getJSON(base_url+'index.php/iprdb/ajax_get_row/'+entry_id, function(data){
    if(!data.success) {
        alert('server error. please try again or contact support');    
    } else {
         $.each(data.table_columns, function(i, item) {
             var myVar = item; // gets table column name ex: address
             $('#'+myVar).val(data.myVar); // stores address into input with id #address
         });                    
    }    
});

那么是否可以使用这种方法访问 data.address ?

【问题讨论】:

    标签: jquery json


    【解决方案1】:

    我知道了:

    var myVar = item;
    $('#'+myVar).val(data[myVar]);
    

    :)

    【讨论】:

    • 干得好:),你不需要myVar,因为它和item一样,你可以直接写data[item]。不要忘记勾选此选项作为正确答案。
    猜你喜欢
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 2021-10-07
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多