【问题标题】:Display json_encode array from ajax result从 ajax 结果显示 json_encode 数组
【发布时间】:2022-06-19 16:25:27
【问题描述】:

我有这个结果

{"policy":[{"id":"1","policy_name":"Policy 1","description":"Testing","status":"Active","valid_until":"2022-05-18","tags":"Test","active":"0","date_added":"2022-05-18 05:36:02"}]}

我想显示数组中的policy_name,我尝试使用这个alert(response['policy'].policy_name); 来提醒它,但我有一个错误。

43:4801 Uncaught TypeError: Cannot read properties of undefined (reading 'policy_name')

更新

这是我的全部代码:

AJAX

$("*[id^='pol_action']").each(function() {
            $(this).change(function(){ 
                var value = $(this).val();
                var id = $('option:selected', this).attr('r-id');
               

                if($(this).val() == 'edit')
                {
                    $.ajax({
                        url: "<?php echo base_url();?>admin/leads/getPolData",
                        type: "POST",
                        data: {id: id},
                        success: function(response){
                            
                        $('#update_policy_modal').modal('show');
                            alert(response['policy'].policy_name);
                            console.log(response);
                        },
                            error: function(data){
                                console.log('error');
                            }
                    });
                }
                else if ($(this).val() == 'delete')
                {
                    
                }
            });
        }); 

控制器

public function getPolData()
    {
        $id = $this->input->post('id');
        
        $policy = $this->leads_model->getDataPol($id);
        $this->page_data['policy'] = $policy;

        echo json_encode($this->page_data);
    }

模型

public function getDataPol($id)
    {
        $where = array(
            'id'       => $id,
          );

        $this->db->select('*');
        $this->db->from('tblpolicies');
        $this->db->where($where);
        $query = $this->db->get();
        return $query->result();
    }

我可以尝试什么来解决这个问题?

【问题讨论】:

  • 您确定将结果用作 JSON 而不是字符串?您能否向我们展示您的代码,以便我们更好地了解发生了什么?
  • 什么代码导致了这个错误?
  • @PierreDemessence 我用控制器功能更新了我的问题
  • @Don'tPanic 我用控制器功能更新了我的问题
  • 在您的 Ajax 调用中输入 dataType:'json',它应该可以工作。如果没有看到 console.dir(response) 吐出什么来了解响应的样子

标签: php html jquery ajax codeigniter


【解决方案1】:

您可以尝试添加 dataType: "JSON" 这样您就不必解析 JSON,如下所示。然后你可以尝试循环遍历数据数组:

$.ajax({
   url: ...,
   type: "POST",
   data: {id:id},
   dataType: "JSON"
   success: function(data){
      $.each(data, function(key, value){
          alert(value.policy_name);
      });
   }
});

【讨论】:

  • 我试过你的代码,但我有undefined,在我的代码上添加了dataType: "JSON",并使用alert(response['policy'][0].policy_name);我已经得到了我需要的东西。策略名称。谢谢!
  • 乐于助人!收到 JSON 响应时,请始终记住添加 dataType: "JSON"。
【解决方案2】:

您正在访问一个数组,所以它应该是:

response['policy'][0].policy_name

【讨论】:

  • 是的,我也试过了,但我遇到了错误Uncaught TypeError: Cannot read properties of undefined (reading '0')
【解决方案3】:

在您的 Ajax 调用中,尝试 json 解析,然后警告该字段:

$.ajax({
          url: "<?php echo base_url();?>admin/leads/getPolData",
          type: "POST",
          data: {id: id},
          success: function(response){
                $('#update_policy_modal').modal('show');
                var obj = $.parseJSON(response);
                alert(obj.policy[0].policy_name);
                console.log(response);
          },
          error: function(data){
                console.log('error');
          }
      });

我编辑了答案,下面是 Javascript:

var json = '{"policy":[{"id":"1","policy_name":"Policy 1","description":"Testing","status":"Active","valid_until":"2022-05-18","tags":"Test","active":"0","date_added":"2022-05-18 05:36:02"}]}';

const obj= JSON.parse(json);

console.log(obj.policy[0].policy_name);

【讨论】:

  • VM2293:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 出现错误
  • 你能详细说明一下标记“o”是什么吗?
  • 我用控制器和 ajax 函数更新了我的问题
猜你喜欢
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
相关资源
最近更新 更多