Javascript Array 的 Foreach 循环,通过 AJAX 查询获得

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12225375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:26:24  来源:igfitidea点击:

Foreach-loop for Array, which got via AJAX-query

javascriptajaxforeachiteration

提问by Eugene Shmorgun

I have the JS-code:

我有JS代码:

$("#select_bank").change(function () {
  selected_bank = $("#select_bank option:selected").text();

  $.ajax({
    type: 'POST',
    dataType: 'html',
    data: {
      selectedBank: selected_bank
    },
    url: '<?= base_url() . 'atm/select_region'; ?>',
    success: function (list_regions) {
      foreach(keyVar in list_regions) {
        alert(list_regions[keyVar]);
      }
    }
  });
});

On callback "succes"s I get the array from server's script - in alert I see the "Array" - so I want to iterate via this array on client-side like I coded above, but when doing I get the error in console - "var keyVar is not defined". As I understand I need to typecast the list_regionsparam as array or some another way to fix it. Please, how to make it better? Thanks!

在回调“成功”中,我从服务器的脚本中获取数组 - 在警报中我看到“数组” - 所以我想像上面编码的那样在客户端通过这个数组进行迭代,但是当我在控制台中得到错误时 - “未定义 var keyVar”。据我了解,我需要将list_regionsparam类型转换为数组或其他一些方法来修复它。请问怎么做比较好?谢谢!

upd: enter image description here

更新: 在此处输入图片说明

回答by Florian Bauer

If I am right you cannot transform the foreach loop into jquery in that way.

如果我是对的,您不能以这种方式将 foreach 循环转换为 jquery。

You should use .each to iterate the values

您应该使用 .each 来迭代值

$.each(list_regions, function(index, value) {
  alert(value);
});

You can find more information here.

您可以在此处找到更多信息。

回答by Daniil Ryzhkov

Javascript doesn't have foreachconstruction. Use $.eachmethod of jQuery

Javascript 没有foreach构造。$.eachjQuery的使用方法

回答by Lucas Green

Try this:

尝试这个:

$("#select_bank").change(function(){
    // The following line was missing a var declaration,
    // Making it an implicit global
    var selected_bank = $("#select_bank option:selected").text();

    $.ajax({
        type:'POST',
        dataType:'html',
        data: { selectedBank: selected_bank },
        url:'<?=base_url().'atm/select_region'; ?>',
        success:function(list_regions){
            var keyVar;
            for(keyVar in list_regions) {
                if (list_regions.hasOwnProperty(keyVar)) {
                    alert(list_regions[keyVar]);
                }
            }
        }
    });

});