今天刚刚学习ajax并且在某处。尝试链接我的PHP链接以使用ajax,以便显示具有该链接ID的数据而不刷新页面。以下是我尝试过的代码。
的index.php
<div class="page">
<ul>
<?php
$sql = <<<EOF
SELECT * FROM addcategory ;
EOF;
$ret = $db->query($sql);
While ($row = $ret->fetchArray(SQLITE3_ASSOC)) {
$catname = $row['catname'];
$catid = $row['catid'];
echo "<li><a href='index.php?category_id=$catid'>$catname</a></li>";
}
?>
</ul>
</div>
<div class="cat_question">response displays here</div>
php脚本
require_once ("db.php");
$db = new MyDb();
$catid = (int)$_GET['category_id'];
$csql = <<<EOF
SELECT * FROM questions WHERE category_id = {$catid};
$cret = $db->query($csql);
While ($crow = $cret->fetchArray(SQLITE3_ASSOC)) {
$catquestion = $crow['question'];
$catans = $crow['answer'];
echo "<div>$catquestion</div><p>$catans</p>";
}
的JavaScript
$('.page a).click(function(e) {
e.preventDefault();
If (window.XMLHttpRequest) {
var xhttp = new XMLHTtpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
If (xhttp.readyState == 4 && xhttp.status == 200) {
var response = xhttp.responseText;
$('.cat_question').html(response);
}
};
xhttp.open("GET", "category.php?category_id=$catid", true);
xhttp.send();
});
我知道如果我将xhttp URL更改为category.php?category_id = 1或任何其工作的ID,但这意味着必须为每个标签编写ajax请求。请问解决这个问题的方法是什么。提前谢谢。