【问题标题】:Issue displaying array in Codeigniter - Ajax在 Codeigniter 中显示数组的问题 - Ajax
【发布时间】:2013-03-18 13:32:29
【问题描述】:

我正在尝试使用 codeigniter 在我的网站中实现 AJAX 调用方法,因此当用户单击按钮时,它会实时更新它们。

点击按钮可以工作并显示所有 JSON 数据,但问题是当我尝试显示特定数组时它不会打印出来它显示单个值,例如“h”

我希望能够打印特定的数组,例如包含字符串“Jamie”的数组

任何帮助将不胜感激

控制器

public function insertJSON()
    {
        $this->load->model("values");
        $queryresults = $this->values->getDb();

        $arr = array();
        $arr2 = array();


        foreach($queryresults as $row)
        {
            $arr[] =  $row->post;
            $arr2[] = $row->img;
        }

                    $data = array();
                    $data[] = $arr;
                    $data[] = $arr2;

                    echo json_encode($data);
    }

查看

<script type='text/javascript' language='javascript'>
  $('#getdata').click(function () {
    $.ajax({
      url: '<?php echo base_url().'index.php/welcome/insertJSON';?>',
      async: false,
      type: "POST",
      success: function(data) {
        $('#result_table').html(data[1]);
      }
    })
  });
</script>

变量的Vardump

array(2) {
  [0]=>
  array(4) {
    [0]=>
    string(5) "Jamie"
    [1]=>
    string(4) "Mark"
    [2]=>
    string(5) "James"
    [3]=>
    string(5) "hello"
}
[1]=>
  array(4) {
    [0]=>
    string(16) "oliver@hotmail.com"
    [1]=>
    string(15) "jakie@hotmail.com"
    [2]=>
    string(15) "mark@hotmail.com"
    [3]=>
    string(16) "james@hotmail.com"
}
}

【问题讨论】:

  • 你必须遍历 JSON 对象
  • data[1] 映射到您添加到 $data 数组中的第二个数组。您需要通过data[0][0] 获得jamiedata[1][0] 获得oliver@hotmail.com
  • 我想我必须尝试 'data[0][0]' 来获取 jamie,但它却显示“

标签: php ajax codeigniter jquery


【解决方案1】:

如果您想要display a specific array,请使用[] 运算符

$('#result_table').html(data[0][0]); //will print Jamie
$('#result_table').html(data[0][3]); //will print hello
$('#result_table').html(data[1][1]); //will print jakie@hotmail.com

【讨论】:

    【解决方案2】:

    尝试在您返回的数据上运行:

    data = JSON.parse(data);
    

    所以:

    success: function(data) {
        data = JSON.parse(data);
        $('#result_table').html(data[1]);
    }
    

    【讨论】:

      【解决方案3】:

      一些信息:要正确获取 JSON,您应该在输出之前设置输出 TYPE,如下所示:

      $this->output->set_content_type('application/json');
      

      然后像这样设置输出:

      $this->output->set_output(json_encode($data));  
      

      但是,根据您的 var dump $data[1] 将显示 Object[] 并且上述所有答案都是正确的。 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-09
        • 2019-03-13
        • 1970-01-01
        • 2016-08-25
        • 2011-11-12
        • 2011-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多