我以json_encode格式返回数据并尝试在ajax中记录输出,但是得到解析错误。

时间:2017-04-27 11:25:06

标签: php jquery mysql json ajax

我的模型 - 我从Mysql数据库获取数据并将其返回到控制器

public function getCharges(){
    $where = "charge_type  = 'variable';
    $data = $this->read('charges',$where);
    return $data;
}

我的控制器 - 这里我将json格式的数据编码为ajax

if (isset($_POST['method']) &&  $_POST['method'] == 'getCharges'){
     $this->load->model('Apiweb_m');
     $data = $this->Apiweb_m->getCharges();
     echo json_encode($data);
}

我的AJAX

var method = "getCharges";
$.ajax({
    type: 'POST',
    data: 'method='+method,
    url : api_url+"apiweb",
   /* dataType: "json",*/
    success:function(msg){
        var data =  $.parseJSON(msg);
        console.log(data);// here iam getting Parse error 
    },
    error:function(Xhr, status, error){
        console.log(Xhr);
        console.log(status);
        console.log(error);
    }

2 个答案:

答案 0 :(得分:0)

将模型中的函数更改为:

public function getCharges(){
    $where = "charge_type  = 'variable'";
    $data = $this->read('charges',$where);
    return $data;
}

和ajax:

var method = "getCharges";
$.ajax({
    type: 'POST',
    data: {method:method},
    url : api_url+"apiweb",
    dataType: "json",
    success:function(msg){
        var data =  $.parseJSON(msg);
        console.log(data);// here iam getting Parse error 
    },
    error:function(Xhr, status, error){
        console.log(Xhr);
        console.log(status);
        console.log(error);
    }

答案 1 :(得分:0)

你必须设置dataType ajax属性json.Hope你会这样做。

var method = "getCharges";
$.ajax({
    type: 'POST',
    data: 'method='+method,
    url : api_url+"apiweb",
    dataType: "json",
    success:function(msg){
        var data =  $.parseJSON(msg);
        console.log(data);// here iam getting Parse error 
    },
    error:function(Xhr, status, error){
        console.log(Xhr);
        console.log(status);
        console.log(error);
    }