显示ajax结果中的json_encode数组



我有这个结果

{"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();
}

我可以尝试解决这个问题吗?

您可以尝试添加dataType: "JSON"所以你不需要解析JSON,如下所示。然后可以尝试遍历数据数组:

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

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

response['policy'][0].policy_name

在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);

最新更新