[英]Get data from mysql database using php and jquery ajax
I want to get data from mysql database using php and jquery ajax. 我想使用php和jquery ajax从mysql数据库中获取数据。 'process.php' is the php file which connects to database and get mysql data.
“ process.php”是连接到数据库并获取mysql数据的php文件。 It works when it is run separately, but when called using ajax it doesn't work.
当它单独运行时它可以工作,但是当使用ajax调用时它不起作用。 Can someone please help to correct error?
有人可以帮忙纠正错误吗? Here is my html file:
这是我的html文件:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function showRoom(){
$.ajax({
type:"POST",
url:"process.php",
data:{action:showroom},
success:function(data){
$("#content").html(data);
}
});
}
showRoom();
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Here is my process.php file 这是我的process.php文件
<?php
$link=mysqli_connect("localhost","root","raspberry","homebot");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
$action=$_POST["action"];
if($action=="showroom"){
$query="SELECT * FROM user";
$show=mysqli_query($link,$query) or die ("Error");
while($row=mysqli_fetch_array($show)){
echo "<li>$row['name']</li>";
}
}
?>
There are two syntax errors in your ajax call: 您的ajax调用中有两个语法错误:
$(document).ready(function(){
function showRoom(){
$.ajax({
type:"POST",
url:"process.php",
data:{action:"showroom"},
success:function(data){
$("#content").html(data);
}
});
}
showRoom();
});
Keep in mind that jQuery's ajax expects an object as parameter. 请记住,jQuery的ajax需要一个对象作为参数。 Inside an object the syntax is
在对象内部的语法是
{ key : value }
You had type="POST" which is correct in declarative syntax, but incorrect when defining an object key. 您输入的类型=“ POST”在声明性语法中正确,但是在定义对象键时不正确。
Second, the data property of the aforementioned object should be an object too. 其次,上述对象的数据属性也应该是一个对象。 So instead of action=showroom it should be
因此,与其说是action = showroom,不如说是
{action:"showroom"}
you did mistake in your code: 您在代码中犯了错误:
echo "<li>$row['name']</li>";
This should be: 应该是:
echo "<li>".$row['name']."</li>";
try that... 试试...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.