0

我正在尝试使用 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"
}
}
4

3 回答 3

1

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

data = JSON.parse(data);

所以:

success: function(data) {
    data = JSON.parse(data);
    $('#result_table').html(data[1]);
}
于 2013-03-18T15:17:23.217 回答
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
于 2013-03-18T13:43:59.293 回答
0

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

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

然后像这样设置输出:

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

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

于 2013-03-21T02:29:11.553 回答