[英]Ajax call giving error on parsing json response; codeigniter
Seems very simple but giving unknown error in ajax success result when trying to parse json response. 似乎非常简单,但是在尝试解析json响应时,ajax成功结果中给出了未知错误。 Error Msg: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data See below code: View: 错误消息:语法错误: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);
}
});
}
Controller: 控制器:
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);
}
Model: 模型:
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();
}
}
Response of ajax: ajax的响应:
Array
(
[reg] => stdClass Object
(
[usertype] => LOW - GS20
)
)
{"reg":{"usertype":"LOW - GS20"}}
Remove this in your controller. 在控制器中删除它。 You're outputting a PHP object and a JSON object, Ajax will only read a JSON object. 您正在输出一个PHP对象和一个JSON对象,Ajax将只读取一个JSON对象。
print_r($result);
If you specify dataType: json, you have to give it json. 如果指定dataType:json,则必须给它json。
Also unless I'm missing something you don't need this: 另外,除非我缺少任何东西,否则您不需要:
parsedobj = JSON.parse(result);
You can just use your object without parsing it. 您可以只使用对象而无需解析它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.