【发布时间】:2017-11-11 14:00:22
【问题描述】:
看起来很简单,但在尝试解析 json 响应时,ajax 成功结果中会出现未知错误。错误消息:SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符 见下面的代码: 查看:
function getUsertype(){
var region= $('#regionSel option:selected').text();
$.ajax({
type:"GET",
url: "<?php echo base_url('Pricecomparison/getUsertype'); ?>",
data:{ "region":region},
contentType: "application/json",
datatype: "json",
success: function(result){
//parsedobj = JSON.parse(result);
console.log(result);
parsedobj = JSON.parse(result);
var appenddata="<option value = '0'>Select User Type</option>";
var appendmetertype;
if (parsedobj.reg)
{
$.each(parsedobj.reg, function(index, value)
{
appenddata += "<option value = '" + value.usertype + "'>" + value.usertype + " </option>";
});
$('#usertypeSel').html(appenddata);
}
else
{
$('#usertypeSel').html(appenddata);
for (i=0; i<=4; ++i){
appendmetertype="<option value = '0'>Select Meter Type "+i+"</option>";
$("#MeterTypeVar"+i+"Sel").html(appendmetertype );
}
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
控制器:
function getUsertype()
{
$this->load->model('Settings_model');
$region = $this->input->get('region');
$result = array("reg" => $this->Settings_model->getSelectedUsertype($region));
print_r($result);
echo json_encode($result);
}
型号:
public function getSelectedUsertype($region)
{
#Create main query
$this->db->select('usertype');
$this->db->where('region', $region);
$this->db->group_by('region','usertype');
$q = $this->db->get('res_price');
if ($q->num_rows()> 0 )
{
return $q->row();
}
}
ajax 的响应:
Array
(
[reg] => stdClass Object
(
[usertype] => LOW - GS20
)
)
{"reg":{"usertype":"LOW - GS20"}}
【问题讨论】:
标签: php json ajax codeigniter