AJAX自定义错误处理代码问题


AJAX Custom error handling Code issue

当页面加载成功数据时,我的Code Igniter PHP页面returns json_encode查询。当找不到记录时,我做了一个json_encode。但我不知道如何将我的无记录错误传递给jQuery

PHP

if (($query->num_rows() > 0) && ($counter > 0)){            
        echo(json_encode($query->result()));                      
        $counter = 0;                        
    } else {            
        //return false;
        $response["error"] = 1;
        $response["error_msg"] = "NO records found";
        echo json_encode($response);
    }}

JQuery

$.ajax({
  url: <? base_url() ?> +'main/data',
  dataType: "JSON",
  type: "POST",
  success: function(retdata) { //working 
    $.each(retdata, function(i) {
           $("#main_div").append('<div>' + retdata[i].name + '<br>' + retdata[i].marks+ '</div>'); 
    });
  }
});

控制器:

public function controller_function()
{
    //$query = your get query code
    $response = array(
        'result'    => array(),
        'error_msg' => '',
    );
    if ($query->num_rows() > 0)
    {
        $response['result'] = $query->result();
    }
    else
    {
        $response['error_msg'] = 'NO records found';
    }
    echo json_encode($response);
}

Javascript:

$.ajax({
    url: <? base_url() ?> +'main/data',
    dataType: "JSON",
    type: "POST",
    success: function (retdata)
    {
        if (retdata.error_msg)
        {
            alert(retdata.error_msg);
        }
        else
        {
            $.each(retdata.result, function (i)
            {
                $("#main_div").append('<div>' + retdata.result[i].name + '<br>' + retdata.result[i].marks + '</div>');
            });
        }
    }
})