我知道这里有很多问题已经解决了我的问题;但是,我试图通过一个链接实现它,我似乎无法使它工作。
我有一个名为tbData
的表格,其中的列名为firstName
& lastName
;我试图从中选择一个随机记录,我正在使用以下代码:
JavaScript的:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function randomfunction() {
$.get("random.php");
return false;
}
</script>
HTML:
<span style="color:#F0E6C3; font-size:30px; font-family: Trajan Pro;">
<a href="#" onclick="randomfunction();">RANDOMIZER!</a>
</SPAN>
PHP:
<?php
$con=mysqli_connect("localhost","root","","dbPos");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL " . mysqli_connect_error();
}
$random = mysqli_query($con,"SELECT * FROM tbData order by RAND() LIMIT 1");
$row = mysqli_fetch_array($random);
while ($row = mysql_fetch_array($random))
{
echo $row['firstName'];
mysqli_close($con);
?>
我正在尝试在我的HTML文件上的 RANDOMIZER!链接下面显示firstName和lastName作为字符串,但点击它后,没有任何反应;我错过了什么吗?
答案 0 :(得分:0)
由于您限制了1个mySQL请求,因此请删除{} {} echo $row['firstName'];
<?php
$con=mysqli_connect("localhost","root","","dbPos");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL " . mysqli_connect_error();
}
$random = mysqli_query($con,"SELECT * FROM tbData order by RAND() LIMIT 1");
$row = mysqli_fetch_array($random);
echo $row['firstName'];
mysqli_close($con);
?>
对于html / jquery部分如下:
<!doctype html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<span style="color:#F0E6C3; font-size:30px; font-family: Trajan Pro;">
<a href="#" class=randomizer>RANDOMIZER!</a>
</span>
<p class=result></p>
<script>
$(".randomizer").click(function(){
$.get("random.php", function(data, status){
$('.result').html(data);
});
});
</script>
</body>
</html>
你走了。
答案 1 :(得分:0)
您应该在.$get()
中回复:
$.get('random.php', (results) => {
// results will equal $row['firstName'] now
});
如果您需要这两个值,我建议您将回声更改为
echo json_encode($row);
然后在获取回调中使用JSON.parse(results)