【发布时间】: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