テーブル (mysql) から結果を返すために ajax を使用しています。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() を使用すると、そうではないことが証明されました。
無関係なコードをここから遠ざけるために最善を尽くしました。どんな助けでも大歓迎です。ありがとうございました。