我是一个初学者,我想知道如何在BootstrapButton点击上显示数据库中的随机行。
下面是我的代码:
<h3 id="myHeader">Press the button below to display a name</h3>
<script>
function displayResult() {
document.getElementById("myHeader").innerHTML =<?php $row["Name"] ?>;
}
</script>
<button type="button" class="btn btn-primary" onclick="displayResult()">Another One</button>发布于 2017-08-09 17:54:31
您必须创建一个PHP页面,该页面从一个表中获取一个随机项目并输出结果
SELECT * FROM table ORDER BY RAND() LIMIT 1然后,在单击按钮时,您希望创建对页面的Ajax请求并显示结果。为此,我将使用JQuery
$.ajax({
url: "random.php",
success: function(response){
$('#myHeader').html(response);
}
})发布于 2017-08-09 18:12:03
您需要执行一个php脚本并获取该行,然后使用ajax获取响应。
$.ajax({
url: "path_to_your_file",
success: //your_Logic
})现在,您已经在打开php脚本后发送了一个请求,并等待响应。
var your_request= new XMLHttpRequest();
your_request.open("GET","your_file.php="data_var_name_in_php="+data ...);
your_request.send();
your_request.onreadystatechange = function result() {
document.getElementById("myHeader").innerHTML = your_request.responseText;
}我建议你先测试你的php脚本,看看在你的本地服务器上能得到什么作为响应文本。有关更多信息,请参阅Ajax文档:http://api.jquery.com/jquery.ajax/
发布于 2017-08-09 18:00:12
您可以使用以下库通过JS连接到数据库MySQL:http://www.mysqljs.com/
这是用于连接的代码:
MySql.Execute(
"mysql.yourhost.com",
"username",
"password",
"database",
"select * from Users",
function (data) {
console.log(data)
});https://stackoverflow.com/questions/45587188
复制相似问题