三行代码  ›  专栏  ›  技术社区  ›  Haryor Torlah

从get请求读取javascript中的json

  •  0
  • Haryor Torlah  · 技术社区  · 4 天前

    $.ajax({
    type: "GET",
    url: m_url+"bank_trans/get_banks/",
    credentials: 'include', 
    headers: {
        'AccessToken': acc,
    },
    success:function(data) {
      console.log(data)
    
      for (i=0; i<data.length; i++){
         console.log(
             data.total_amount + "<br />"
         );
      }
    
    
    }
    
    });
    

    json转储的输出,来自console.log

    [{"total_amount": 1254275355.95, "BANK_NAME": "FIRST BANK"}, {"total_amount": 49307548.55, "BANK_NAME": "GT BANK"}, {"total_amount": 100000.00, "BANK_NAME": "STANBIC IBTC BANK"}, {"total_amount": 79100000.00, "BANK_NAME": "STERLING BANK"}, {"total_amount": 50133150.68, "BANK_NAME": "UBA"}, {"total_amount": 13000000.00, "BANK_NAME": "ZENITH BANK"}]
    

    谢谢

    1 回复  |  直到 4 天前
        1
  •  2
  •   azro    4 天前

    data 是一个JSON内容:一个字符串,您需要将其作为JS结构加载,这里是一个对象列表

    简单解

    data[i].total_amount 而不是 data.total_amount

    let data = '[{"total_amount": 1254275355.95, "BANK_NAME": "FIRST BANK"}, {"total_amount": 49307548.55, "BANK_NAME": "GT BANK"}, {"total_amount": 100000.00, "BANK_NAME": "STANBIC IBTC BANK"}, {"total_amount": 79100000.00, "BANK_NAME": "STERLING BANK"}, {"total_amount": 50133150.68, "BANK_NAME": "UBA"}, {"total_amount": 13000000.00, "BANK_NAME": "ZENITH BANK"}]'
    data = JSON.parse(data)
    for (i=0; i<data.length; i++){
        console.log(data[i].total_amount);
    }

    更好的解决方案

    jquery.ajax

    dataType: "json" 从JSON自动加载

    $.ajax({
        type: "GET",
        dataType: "json",
        url: m_url + "bank_trans/get_banks/",
        credentials: 'include',
        headers: {
            'AccessToken': acc,
        },
        success: function(data) {
            console.log(data)
            for (i=0; i < data.length; i++){
                console.log(data[i].total_amount);
            }
        }
    });