阿贾克斯:我能';t使用json_encode从PHP获取数据
我在使用Ajax从PHP检索数据时遇到问题。我陷入困境,花了很多时间试图找出问题所在 以下是我的php代码:阿贾克斯:我能';t使用json_encode从PHP获取数据,php,jquery,ajax,json,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');
<?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);
?>
以下是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>
$(文档).ready(函数(){
/*从PHP文件中检索数据*/
$.ajax({
url:“ajax/default\u chart\u numbers.php”,
cache:false,
数据类型:“json”,
超时:3000,
成功:功能(响应、文本、xhr){
警惕(“一切正常:)”;
},
错误:函数(xmlHttpRequest、textStatus、errorshown){
警报(“错误”+错误抛出);
如果(textStatus=='timeout')
警报(“请求超时”);
},
完成:功能(数据){
y=数据。y;
警报(“id号为“+y”);
}
});
});
执行时,该值未定义。我的意思是,我得到的警告是身份证号码没有定义
我缺少什么?在
json\u encode
中没有true,在json\u decode
中有获取数组的属性,但现在您正在创建一个字符串
改变
print json_encode($json,true);
到
完整的处理程序不获取数据,它有两个参数,XHR对象和statuscode,success处理程序获取数据
$.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");
}
});
在PHP端,通过以下方式发送JSON:
header('Content-Type: application/json');
echo json_encode($json);
可能会将传入数据记录到控制台:
console.log(响应)
console.log(data.y)
result = $.parseJSON (data);
result.y有你的值如果你只打开php文件url,输出是什么?你一定会从错误处理程序或成功处理程序中得到警报?不,不是,数据类型设置为JSON,所以它会自动解析,再次解析会导致错误。@adeneo啊,是的,我忽略了那个。说得好。
header('Content-Type: application/json');
echo json_encode($json);
result = $.parseJSON (data);