我有一个 javascript 文件,我在其中对 foo.php
执行 ajax 请求
为了获得一组mysql结果。
这是我的 javascript 文件。
//foo.js
$(document).ready(function(){
$.ajax({
url:"foo.php",
type:"POST",
data:{
action:"test",
remail:"foo"
},
success:function(data){
var messages = data;
console.log("Ext req");
try{
console.log(JSON.parse(data));
}catch(e){
console.log(data);
}
},
failure:function(){
}
})
});
为了从 php 接收我的结果数组,我执行以下操作:
//foo.php
<?php
if(isset($_POST)){
$action = $_POST['action'];
if(empty($action)){
return;
}
switch($action){
case "test":
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
echo json_encode($ar);
break;
}
}
?>
这会向我的 ajax 请求返回一个对象数组,然后我可以根据需要进行处理。 但是,如果我尝试将 switch 语句内的 php 代码移动到一个函数中并返回该函数的编码结果,我只会得到一个空数组作为响应。 这是我正在尝试的方式:
<?php
function test(){
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
if(isset($_POST)){
$action = $_POST['action'];
if(empty($action)){
return;
}
switch($action){
case "test":
$result = test();
echo json_encode($result);
break;
}
}
?>
知道为什么会这样吗?
更新
$con
是一个来 self include
最佳答案
当您将查询逻辑移动到函数$con
中时,MySQL 的连接对象不可用。在函数中使用 GLOBAL $con;
。
阅读本文以了解 Variable Scope
方法一
使用 GLOBAL
关键字
function test(){
GLOBAL $con;
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
方法二 将参数传递给函数
function test($con){
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
Call it like this:
test($con);
关于javascript - 无法将数组从 php 函数返回到 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43153685/