所以我试图从数据库中检索一些数据,将它们呈现给网页。问题是,即使我使用的代码与我用来检索要加载到同一页面的其他数据的函数相同,但这个新函数根本不起作用。下面是脚本及其php文件的代码。 console.logs显示一个空白数组,并且函数总是失败,所以它总是警告错误。此外,我尝试尝试启动变量与否,总是相同的结果,所以我有点急于求助
脚本
<script>
function databasetoaccordion(){
var arr2=[];
alert('hi');
$.ajax({
type: "POST",
datatype: "json",
url: "databasetaccordion.php",
data: {exhibitid:exhibitid,exhibitname:exhibitname,exhibitsum:exhibitsum,exhibitinfo:exhibitinfo,exhibitphoto:exhibitphoto},
success: function(success){
var arr2 = Array.from(Object.keys(success), k=>success[k]);
console.log(arr2);
alert('cool');
},
error: function(error){
alert("error");
console.log(arr2);
}
});
}
</script>
databasetoaccordion.php
<?php
session_start();
require_once('dbconfig/config.php');
//phpinfo();
?>
<?php
$sql = "SELECT * FROM exhibit JOIN painterarrays ON exhibit.roomid=painterarrays.id WHERE exhibit.roomid=painterarrays.id AND painterarrays.username='". $_SESSION['username']."' ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$exhibitid=$row['exhibitid'];
$exhibitname= $row['exhibitname'];
$exhibitsum=$row['exhibitsum'];
$exhibitinfo=$row['exhibitinfo'];
$exhibitphoto=$row['exhibitphoto'];
$ar=array('exhibitid'=>$exhibitid,'exhibitname'=>$exhibitname,'exhibitsum'=>$exhibitsum,'exhibitinfo'=>$exhibitinfo,'exhibitphoto'=>$exhibitphoto);
$c= json_encode($ar);
echo $c;
echo 'hope it works';
}
} else {
echo "0 results";
}
mysqli_close($con);
?>
答案 0 :(得分:0)
所以我稍微修改了你的代码,我让它在我的机器上运行。
首先,在您的PHP文件中,您的数组需要具有键和值,例如...
$ar=array('exhibitid'=>exhibitid,'exhibitname'=>exhibitname,'exhibitsum'=>exhibitsum,'exhibitinfo'=>exhibitinfo,'exhibitphoto'=>exhibitphoto);
注意第一个值周围的引号。 其次,你在php函数的末尾回应一些奇怪的东西。由于它被用作AJAX调用,你唯一想要回应的就是响应。
$c= json_encode($ar);
echo $c;
然后在您的Javascript文件中,您可以删除ajax调用中的data: ....
行,这是不需要的。
最后在您的成功函数中,您只想解析返回
success: function(response){
const array = JSON.parse(reponse);
},
希望这有帮助。