【问题标题】:How to traverse this ajax response as array?如何将此ajax响应作为数组遍历?
【发布时间】:2019-01-11 14:43:11
【问题描述】:

我在代码点火器中使用 ajax 得到以下数组作为响应。

 Array
(
    [0] => stdClass Object
        (
            [monthly_count] => 3
        )

    [1] => stdClass Object
        (
            [monthly_count] => 1
        )

)

//到目前为止我尝试过的是

$.ajax({
            url:"<?php echo base_url();?>Admins/get_monthly_orders",
            type: 'POST',
            //dataType: 'JSON',
            success:function (data) {
                var result = [];
                var array = data;
                console.log(data);
                array.forEach(function(k , v) {
                    var result = v.monthly_count;
                })
                console.log(result);

请帮我遍历得到 3, 1 我需要像这样获取“monthly_count”的值

Array
(
    [0]  =>3


    [1] => 1

)

或者更好的类似的东西

[3, 1]

我的控制器代码是这样的

public function get_monthly_orders(){
        $monthlyOrders = $this->Admin_model->get_monthly_orders();

        if($monthlyOrders){
            print_r($monthlyOrders);
        }
        else{
            return false;
        }
    }

【问题讨论】:

  • 请正确格式化您的问题。
  • @Andy 请检查
  • 显示你的 php 代码。
  • 还告诉我 Admin_model 中的 get_monthly_orders
  • 我认为是data.map(d=&gt;d.monthly_count),但如果不是,则发布console.log(JSON.stringify(data,2,undefined));的输出

标签: javascript arrays ajax codeigniter


【解决方案1】:

尝试将print_r($monthlyOrders) 更改为echo json_encode( $monthlyOrders );。这将以 JSON 格式返回。用JS遍历会容易很多。

如果你想遍历它,你可以:

let result = [];
array.forEach(el => {
  result.push(el.monthly);
})
console.log(result);

【讨论】:

  • 谢谢@adis..我只用json_encode()解决了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 2020-02-12
  • 2019-02-17
  • 1970-01-01
  • 2011-09-16
相关资源
最近更新 更多