【问题标题】:codeigniter access data array in ajax success functionajax成功函数中的codeigniter访问数据数组
【发布时间】:2015-03-18 08:24:06
【问题描述】:

我的问题是我无法访问从控制器返回到 ajax 成功函数的数组。

这里是我的控制器代码:

function get_slot()
{
    $fac_id = 1;
    $date = $this->input->post('date');

    $this->load->model('booking_model');
    $result = $this->booking_model->get_slot_availablity($date, $fac_id );  
    $data['booking'] = $result['row'];

    echo json_encode($data);
}

我的 ajax 函数:

 $.ajax({
          type : "Post",
           url : "<?php echo base_url(); ?>index.php/index/get_slot",
          data : "date="+date,
      dataType : 'json',
       success : function(result)
                {
                    $.each(result, function(index, val) {
                        alert(val.slot_id); 
                    });
                }
       });

我的模型函数:

public function get_slot_availablity($date, $fac_id){

    $q = $this->db->select('*')
    ->from('booking')
    ->where('f_id', $fac_id)
    ->where('date', $date);

    $res['row'] = $q->get()->result();

    return $res;
}

函数显示未定义

【问题讨论】:

  • 检查浏览器控制台,你从服务器得到什么?
  • 不需要header()先alert(result);在你的成功块中然后开始解析你的 json 数据
  • 我已经删除了 header(),并且我添加了 dataType json..但仍然得到未定义的 @RakeshSharma
  • 请列出这个$this-&gt;booking_model-&gt;get_slot_availablity()函数的代码。
  • 我已经编辑了我的问题@Mysteryos

标签: php jquery arrays ajax codeigniter


【解决方案1】:

根据您的最新评论,您的 JS 代码应如下所示:

$.ajax({
      type : "Post",
       url : "<?php echo base_url(); ?>index.php/index/get_slot",
      data : "date="+date,
  dataType : 'json',
   success : function(result)
            {
                $.each(result.booking, function(index, val) {
                    alert(val.slot_id); 
                });
            }
   });

【讨论】:

  • 请您详细解释一下您在上面的最新评论?
  • 您正在回显一个 json 编码的 $data 变量,其中 $data['booking'] 包含您的数据库结果。将数组转换为 JSON,booking 成为您的 result 对象的属性,因此 result.booking
  • 我明白了,我想最好将数组从模型直接返回到结果对象,而不是使用多个对象。谢谢@Mysteryos
  • 确实如此。另外,我建议您远离 CodeIgniter 的活动记录。它可能适用于简单的东西,但对于复杂的 mySQL 查询没有其他选择。使用原始 mySQL 并为您的代码库带来统一性。
  • 感谢@Mysteryos 的提示和建议,不胜感激:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多