我正在使用 ajax 从表(mysql)返回结果。Ajax 调用是使用 jquery 进行的。使用 PDO 访问数据库。
PHP
function fetchQuestions() {
$database = "answerMe"; // the name of the database.
$server = "127.0.0.1"; // server to connect to.
$db_user = "name"; // mysql username to access the database with.
$db_pass = "password"; // mysql password to access the database with.
$table = "questions";
$result = "";
try {
$testh = new PDO ("mysql:host=$server;dbname=$database", $db_user, $db_pass);
$testh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$testh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "select COUNT(*) from questions";
$pstatement = $testh->prepare($sql);
$success = $pstatement->execute();
$num = $pstatement->fetchColumn();
$sql = "select * from $table";
$pstatement = $testh->prepare($sql);
$success = $pstatement->execute();
print("Fetch all of the remaining rows in the result set:\n");
$result = $pstatement->fetchAll(PDO::FETCH_COLUMN, 1);
return $result;
}
catch(PDOException $e)
{
echo "Following error was encountered <br />";
echo $e->getMessage();
}
}
$function = $_POST['function'];
$response = array();
$data = "";
switch($function) {
.
.
.
case('recData'):
//$qs = array('w','k');
$qs = fetchQuestions();
$response['records'] = $qs;
break;
}
echo json_encode($response);
Jquery(ajax部分)
function AjaxReq(){
this.sendSuccess = false;
this.recSuccess = false;
this.send = sendData;
this.rec = recData;
}
.
.
.
function recData() {
$.ajax({
type: "POST",
url: "ajax.php",
data: { 'function': 'recData',
},
dataType: "json",
success: function(data){
alert('rec succeeded');
this.recSuccess = true;
for(var i = 0; i < data.records.length; ++i) {
$("#details").append(data.records[i]);
}
},
});
}
Jquery(调用ajax)
$(document).ready(function(){
var reqTest = new AjaxReq();
$("#done").bind('click',function(){
reqTest.rec();
});
});
在 PHP 代码中,案例 'recData',如果我取消注释 //$qs = array('w','k');,我会得到结果。
这让我得出结论,也许 $qs 可能不是一个数组。但是使用 is_array(),它被证明不是这样。
我已尽我所能将不相关的代码远离这里。任何帮助,将不胜感激。谢谢你。