使用ajax将数组值从PHP传递到JavaScript



我有一个PHP文件,其中包括一个数组,它的数据是从数据库中检索的。

这是PHP文件dashboard.php中的数组

echo $stat= json_encode(array( 
0 => $posts['tot'], 
1 => $partners['pap'], 
2 => $messages['mem'], 
));

该阵列的输出为:["12","5","11"]

另一方面,我有一个javascript文件,它应该使用ajax接收这些数据,然后将其输出为对象数据,以在dashboard.php页面上的图表中显示

这是javascript文件中的ajax代码:

function () {
$.ajax({
url: 'dashboard.php',
type: 'get',
data: { n1: n1, n2: n2, n3: n3 },
dataType: 'JSON',
success: function (response) {
// selecting values from response Object
var n1 = response.n1;
var n2 = response.n2;
var n3 = response.n3;
}
});
});

我知道缺少了一些东西,如何定义来自PHP文件的数据,这是我的问题,我无法解决。

我看了很多教程,但我仍然很困惑,我无法获得它。

谢谢。

在PHP输出中:

["12","5","11"]

这三个值显然都是字符串。

您所需要做的就是在将它们发送回客户端之前将其转换为数字(使用intval或类似方法(:

echo $stat = json_encode(array( 
0 => intval($posts['tot']), 
1 => intval($partners['pap']), 
2 => intval($messages['mem']), 
));

接下来,您会遇到另一个问题,即服务器正在传回一个数组,但客户端试图将其当作对象来读取,因此您永远无法获得值。

由于传递回服务器的数据是一个数组["12","5","11"],因此在客户端中,您将希望以数组方式检索它:

{
...otherAjaxOptions,
success: function(response){
var n1 = response[0];
var n2 = response[1];
var n3 = response[2];
/* or using ES6 way */
var [n1, n2, n3] = response;
}
}

如果response不是一个数组,那么您的服务器可能正在将响应转换为一个更结构化的对象。在这种情况下,只需检查数组在response中的位置,并以相同的方式检索它。

考虑根据ajax脚本的要求重新定义关联数组的键,即"n1"、"n2"、"n3"。

删除ajax后的右括号和分号,并将ajax重写为一个函数,该函数从成功函数处理程序返回响应。

命名函数后还返回函数的ajax调用结果,现在它是一个匿名的未命名函数。除非您想使用即时调用函数表达式(IIFE(进行调用,否则请使用

(function(){})();

index.html

<html> 
<head> 
<title>Ajax</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
<script>
function ajax() {
return $.ajax({
url: 'dashboard.php'
}).done(function(response) {
// selecting values from response Object
var n1 = response.n1;
var n2 = response.n2;
var n3 = response.n3;
return response;
});
}
$('document').ready(function(){  
ajax().then(function(result){
$("body").html("<pre>"+result+"</pre>");
});
});
</script>
</head>
<body>
</body>
</html>

dashboard.php

<?php
$posts = [];
$partners = [];
$messages = [];
$posts['tot'] = '12';
$partners['pap'] = '5';
$messages['mem'] = '11';

echo json_encode(array( 
'n1' => $posts['tot'], 
'n2' => $partners['pap'], 
'n3' => $messages['mem'] 
));

查看故障演示https://glitch.com/~微光支票

最新更新