使用jQuery填充选择框时出现“未定义”错误

时间:2019-12-06 20:23:45

标签: javascript jquery

我有这段代码可以使用jquery向选择框填充银行列表

 let bank_dropdown = $('#bank');

bank_dropdown.empty();


bank_dropdown.prop('selectedIndex', 0);

const bank_url = 'https://ravesandboxapi.flutterwave.com/v2/banks/NG?public_key=FLWPUBK-3f**************1d15e97-X';

// Populate bank_dropdown with list of banks
$.getJSON(bank_url, function (data) {
  $.each(data, function (key, entry) {
    bank_dropdown.append($('<option></option>').attr('value',  entry.data.Banks.Code).text(entry.data.Banks.Name));
  })
});

html


 <div class="form-group">
     <small><b><label class="float-left" for="inputCategory">Bank</label></b></small>
      <select name="bank" id="bank" class="form-control form-control-sm" required="true">

    </select>
  </div>

上面的url返回的响应看起来像这样

{
  "status": "success",
  "message": "SUCCESS",
  "data": {
    "Banks": [
      {
        "Id": 132,
        "Code": "560",
        "Name": "Page MFBank"
      },
      {
        "Id": 133,
        "Code": "304",
        "Name": "Stanbic Mobile Money"
      }
...
    ],
  }
}

但是由于某些原因,我一直在控制台中收到此错误

  

未捕获的TypeError:无法读取未定义的属性“银行”

2 个答案:

答案 0 :(得分:1)

看起来像您的data.data对象本身是一个对象,而不是数组,并且您正在尝试对其进行迭代。

{
  "status": "success",
  "message": "SUCCESS",
  "data": {      <- This is an object, not an array
    "Banks": []  <- This is the array
  }
}

尝试一下(使用data.data.Banks):

$.each(data.data.Banks, function (key, entry) {
    bank_dropdown.append($('<option></option>').attr('value',  entry.Code).text(entry.Name));
})

如果有帮助,为清楚起见,您可以将响应对象重命名为“ res”或“ response”

$.getJSON(bank_url, function (res) {
    // now use res.data.Banks
    $.each(res.data.Banks, function (key, entry) {
        bank_dropdown.append($('<option></option>').attr('value',  entry.Code).text(entry.Name));
    })
});

答案 1 :(得分:1)

您正在迭代错误的对象。在此处查看代码段:

const data = {
  "status": "success",
  "message": "SUCCESS",
  "data": {
    "Banks": [{
      "Id": 132,
      "Code": "560",
      "Name": "Page MFBank"
    }, {
      "Id": 133,
      "Code": "304",
      "Name": "Stanbic Mobile Money"
    }],
  }
};

const bank_dropdown = $("#bank_dropdown");

$.each(data.data.Banks, function(key, entry) {  
  bank_dropdown.append(
        $('<option></option>').val(entry.Code).html(entry.Name)
    );
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="bank_dropdown">
</select>