我试图通过调用function.php来查询数据库,从而使用Json从数据库中获取数据。我遇到了一个问题,找出我如何在function.php文件中指定一个特定的函数来完成工作。
下面是我的Jquery和function.php,目标是让Json使用function.php中的getlist()。
请帮助我一直试图理解这一点。
Jquery功能:
$.getJSON( "public/includes/functions.php", function( data ) {
var items = [];
$.each( data, function( key, val ) {
console.log('data:' + key + ' And ' + val);
});
});
PHP功能:
function getlist(){
require "dbconn.php";
$result = $stdb->get_results("SELECT id, name FROM supplements");
$stdb->show_errors();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
} else {
echo "0 results";
}
$js_array = json_encode($array);
echo $js_array;
mysqli_close($conn);
}
答案 0 :(得分:1)
$.getJSON( "public/includes/functions.php?myfun=1", function( data ) {
var items = [];
$.each( data, function( key, val ) {
console.log('data:' + key + ' And ' + val);
});
});
<?php
if(isset($_GET)){
if(isset($_GET['myfun'])){
getlist();exit;
}
}
function getlist(){
require "dbconn.php";
$result = $stdb->get_results("SELECT id, name FROM supplements");
$stdb->show_errors();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
} else {
echo "0 results";
}
$js_array = json_encode($array);
echo $js_array;
mysqli_close($conn);
}
?>
答案 1 :(得分:0)
function getlist(){
require "dbconn.php";
$result = $stdb->get_results("SELECT id, name FROM supplements");
$stdb->show_errors();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
} else {
echo "0 results";
}
$js_array = json_encode($array);
echo $js_array;
mysqli_close($conn);
}
//You need to call your function
getlist();