【问题标题】:Get data from mysql database using php and jquery ajax使用 php 和 jquery ajax 从 mysql 数据库中获取数据
【发布时间】:2014-05-03 19:56:32
【问题描述】:

我想使用 php 和 jquery ajax 从 mysql 数据库中获取数据。 'process.php'是连接数据库并获取mysql数据的php文件。它在单独运行时有效,但在使用 ajax 调用时它不起作用。有人可以帮忙纠正错误吗?这是我的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>

这是我的 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>";
    }
}
?>

【问题讨论】:

  • 什么不起作用?你有错误吗?它是什么?你做了什么调试?
  • 我没有收到错误。但没有打印任何内容。预计从 mysql 数据库打印 ($row[name])
  • while 之前添加if(!mysqli_num_rows($show)) echo "no result"。也许查询没有返回任何东西?或者尝试将name 放在引号中。
  • 已添加。但结果仍然相同
  • 不要在字符串中使用数组:将echo "&lt;li&gt;$row['name']&lt;/li&gt;";替换为echo "&lt;li&gt;".$row['name']."&lt;/li&gt;";

标签: javascript php jquery mysql ajax


【解决方案1】:

您的 ajax 调用中有两个语法错误:

$(document).ready(function(){
    function showRoom(){
        $.ajax({
            type:"POST",
            url:"process.php",
            data:{action:"showroom"},
            success:function(data){
                $("#content").html(data);
            }
        });
    }
    showRoom();
});

请记住,jQuery 的 ajax 需要一个对象作为参数。对象内部的语法是

{ key : value }

您的 type="POST" 在声明性语法中是正确的,但在定义对象键时不正确。

其次,上述对象的数据属性也应该是一个对象。所以应该是而不是 action=showroom

{action:"showroom"}

【讨论】:

    【解决方案2】:

    你的代码有错误:

     echo "<li>$row['name']</li>";
    

    这应该是:

     echo "<li>".$row['name']."</li>";
    

    试试看……

    【讨论】:

      猜你喜欢
      • 2018-07-07
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2019-11-26
      相关资源
      最近更新 更多