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

时间:2014-03-30 16:39:05

标签: php jquery ajax json

我在使用Ajax从PHP检索数据时遇到问题。我很困难,并且花了很多时间试图找出问题所在。

这是我的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文件的输出是:

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

这是jQuery代码:

<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>

执行时,值未定义。我的意思是,我得到的提醒是<​​em> ID号未定义。

我缺少什么?

3 个答案:

答案 0 :(得分:2)

json_encode中没有,json_decode中有一个数组,但现在你正在创建一个字符串

变化

print json_encode($json,true);

echo json_encode($json);

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

$.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");
    }
});

答案 1 :(得分:1)

在PHP方面,发送JSON:

header('Content-Type: application/json');
echo json_encode($json);

可能将传入的数据记录到控制台:

  1. 内部成功:添加console.log(response)
  2. 内部完成:添加console.log(data.y)

答案 2 :(得分:-1)

缺少这个: https://api.jquery.com/jQuery.parseJSON/

尝试使用:

 result = $.parseJSON (data);

result.y有你的价值

相关问题