无法在视图或警报中显示JSON成功输出

时间:2018-07-17 19:07:36

标签: javascript php jquery json codeigniter-3

我正在使用CodeIgniter,我有三个输入字段,分别是名称,emp_id,crm_id。我正在输入id值并将其发送到控制器,以使用AJAX和JSON获取与该id相关的所有信息。现在的问题是,我在“网络”选项卡中获得了正确的输出,但是即使警报也没有显示在JSON中,也无法在视图页面中显示。

有时由于JSON为空,我遇到了以下错误

 [Show/hide message details.] SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

我认为JSON存在一些问题。

Ajax

 $("form[name='search_addSalaryrecord']").validate({ 
// errorElement: 'div', 
submitHandler: function(form) { 
//alert(baseUrl); 
var employee_name = $('#employee_name').val(); 
var crm_id = $('#crm_id').val(); 
var employee_id = $('#employee_id').val(); 
$.ajax({ 
url: baseUrl + "/Employee_control/search_addSalaryrecord", 
method: "POST", 
dataType: "json", 
data: {employee_name: employee_name,crm_id:crm_id,employee_id:employee_id}, 
success: function(response) { 

//$('.search_record tbody').html(response); 
// var data = JSON.parse(response); 

//alert(data.status); 
if (response.status === 'error') 
{ 
alert(response.msg); 

} 

if (response.status === 'success') { 
//alert('data avaliable'); 
alert(response.records); 
console.log(response.records); 

} 
} 
//error: function(error) { console.log(error); } 

}); 
} 
});

控制器

public function search_addSalaryrecord() 
{ 
$employee_name=trim($this->input->post('employee_name')); 
$emp_crmid=trim($this->input->post('crm_id')); 
$employee_id=trim($this->input->post('employee_id')); 

if((!empty($employee_name)) ||(!empty($emp_crmid)) || (!empty($employee_id))){ 
$arr_result =$this->Employee_model->get_salary_search_emp_id($employee_name,$emp_crmid,$employee_id); 
if (!empty($arr_result)){ 
foreach ($arr_result as $row) 
{ 
$result[] = array(  
"name" => $row->firstname.' '.$row->lastname, 
"mobileno" => $row->mobileno, 
"email_id" => $row->email_id, 
"employee_id" => $row->employee_id, 
"month_year" => $row->month.' '.$row->year
); 
} 
//print_r($result); 
$respnonse['status'] = 'success'; 
$respnonse['records'] = $result; 
} 
else 
{ 
$respnonse['status'] = "error"; 
$respnonse['records'] = "No record found"; 
} 
} 
echo json_encode($arr_result); 
exit; 
}

1 个答案:

答案 0 :(得分:0)

希望这对您有帮助:

在您的ajax中使用dataType: "json"以避免进一步解析响应,并从您的控制器返回json_encode的{​​{1}}数据

您的exit应该是这样的:

ajax

您控制器的方法$("form[name='search_record']").validate({ submitHandler: function(form) { var employee_id = $('#employee_id').val(); $.ajax({ url: baseUrl + "/Employee_control/search_addSalaryrecord", method: "POST", dataType: "json", data: {employee_id:employee_id}, success: function(response) { //alert(data.status); if (response.status == 'error') { alert(response.msg); $('.personel_info').empty(); } if (response.status == 'success') { alert(response.records); $('.personel_info').empty(); $('.personel_info').show(); var trHTML = ''; $.each(data.records, function (i, o){ $('#name_emp').text(o.name); $('#mobileno_emp').text(o.mobileno); $('#employee_email').text(o.employee_email); }); } } }); } }); 应该是这样的:

search_addSalaryrecord