Ajax:我无法通过使用json_encode从PHP获取数据

问题描述:

我在使用Ajax从PHP检索数据时遇到问题.我被困住了,一直花很多时间试图找出问题所在.

I am having issues retrieving data from PHP by using Ajax. I am stuck and have been spending lots of time trying to find out where the problem is.

这是我的php代码:

        <?php //ajax/default_chart_numbers.php
        require_once '../core/db_connection.php';
        $lotto = new Lotto();
        $ultimo_concurso=$lotto->ultimo_concurso('foo');
        $ultimos_numeros_m=$lotto->ultimos_numeros('bar');

        $R1m=$ultimos_numeros_m[1];
        $R2m=$ultimos_numeros_m[2];
        $R3m=$ultimos_numeros_m[3];
        $R4m=$ultimos_numeros_m[4];
        $R5m=$ultimos_numeros_m[5];
        $R6m=$ultimos_numeros_m[6];
        $R7m=$ultimos_numeros_m[7];

        //preparing json
  $json=array('y'=>$ultimo_concurso,'n1'=>$R1m,'n2'=>$R2m,'n3'=>$R3m,'n4'=>$R4m,'n5'=>$R5m,'n6'=>$R6m);
        print json_encode($json,true);
        ?>

PHP文件的输出为:

The output of the PHP file is:

{"y":"2745","n1":"1","n2":"13","n3":"19","n4":"29","n5":"41","n6":"46"}

这是jQuery代码:

And here is the jQuery code:

<script>
$(document).ready(function(){
    /*Retriving data from PHP file*/
    $.ajax({
        url: "ajax/default_chart_numbers.php",
        cache: false, 
        dataType: "json",
        timeout:3000,
        success : function (response, textS, xhr) {
            alert("everything ok :)");
        },
        error : function (xmlHttpRequest, textStatus, errorThrown) {
            alert("Error " + errorThrown);
             if(textStatus==='timeout')
              alert("request timed out");
        },
        complete: function(data){
            y=data.y;
            alert('The id number is '+ y);
        }
    });
});
</script>

执行时,该值未定义.我的意思是,我收到的警报是 ID号未定义.

When executing, the value is undefined. I mean, the alert i get is The id number is undefined.

我想念什么?

json_encode中没有真值,json_decode中没有要获取数组的内容,但是现在您正在创建字符串

There's no true in json_encode, there is in json_decode to get an array, but now you're creating a string

更改

print json_encode($json,true);

echo json_encode($json);

并且完整的处理程序不获取数据,它具有两个参数XHR对象和状态码,成功的处理程序获取数据

and the complete handler doesn't get the data, it has two arguments, the XHR object and the statuscode, the success handler gets the data

$.ajax({
    url: "ajax/default_chart_numbers.php",
    cache: false, 
    dataType: "json",
    timeout:3000,
    success : function (data) {
        y=data.y;
        alert('The id number is '+ y);
    },
    error : function (xmlHttpRequest, textStatus, errorThrown) {
         alert("Error " + errorThrown);
         if(textStatus==='timeout')
             alert("request timed out");
    }
});