$ .ajax没带我的json_encode

时间:2016-03-24 18:44:52

标签: php jquery ajax

retorno json_encode它没有返回任何东西

这是js控制器我想要返回json" retorno"

$.ajax({
    url: 'controll/busqueda.php',
    data: {
        format: 'json',
        "precio_min": "",
        "precio_max": "",
        "rate": "",
        "asignatura": ""
    },
    success: function(retorno) {
        alert(retorno.profesores);
    },
    error: function() {
        alert("aaaaa");
    },
    type: 'GET'
});

这是我调用模型db的php文件,而$ retorno是数据库中的stdClass(),我在其中放入了profesores

if($precio_max != "" || $precio_min != ""){
   $retorno = $busqueda->profesor_precio($precio_min,$precio_max);
}else{
    if($rate != ""){
        $retorno = $busqueda->profesor_rate($rate);
    }else{
        if($asignatura != ""){
            $retorno = $busqueda->profesor_asig($asignatura);
        }else{
            $retorno = $busqueda->profesor();
        }
    }
}

 echo json_encode($retorno, true);

1 个答案:

答案 0 :(得分:2)

1)您的服务器必须使用标头Content-type: application/json返回正确的响应。您可以使用该代码在php中执行此操作:

header('Content-type: application/json');

您必须在任何echo之前发送此标题。

2)为ajax请求设置dataType属性。例如:

$.ajax({
    url: 'controll/busqueda.php',
    dataType: 'json',
    data: {
        param: 'value'
    },
    success: function(retorno) {
        alert(retorno.profesores);
    },
    type: 'GET'
});

3)确保您对controll/busqueda.php的请求返回有效的json数据。检查您的回复http://yourhost.name/controll/busqueda.php它是否返回有效的json?