weixin_33736048 2017-05-25 13:45 采纳率: 0%
浏览 15

PHP将数据发送回AJAX

I'm trying to get data from my database using ajax and php, but whenever I try to get it I get an error with ajax. Here is my code:

HTML

Here is my code where I request the php file.

<body>
    <div id="wrapper">
        <h2>Coffe Shop</h2>
        <p class="bold">Drink orders:</p>

        <ul class="orders">
        </ul>

        <p class="bold">Add an order:</p>
        <p>Drink: <input type="text" id="name"/><input type="submit" id="submit"/></p>

        <button id="refresh">CLICK ME</button>
    </div>

    <script>
        $(function (){
            $("#refresh").on("click", function() {
               $.ajax({
                type: "GET",
                url: "data.php",
                dataType: "json",
                success: function(names){
                    $.each(names, function(name){
                        alert(name);
                    });
                },
                error: function(){
                    alert("error");
                }
           });
        }); 
            });

    </script>
</body>

PHP

Here is my PHP file

<?php

$conn = mysqli_connect("localhost:8080", "root", "", "test1")
    or die("Error with connection");


$sql = "SELECT ime FROM users;";

$result = mysqli_query($conn, $sql);

$row = mysqli_fetch_array($result);
$names = array();

while($row){
    $name = array(
        "name"=> $row['ime']
    );

$names[] = $name;
}

echo json_encode($names);
  • 写回答

1条回答 默认 最新

  • weixin_33711641 2017-05-25 13:55
    关注

    You have an infinite loop in your PHP. You're just fetching one row, and then looping over that same row. Since you never change $row in the loop, it never ends. It should be:

    while ($row = mysqli_fetch_assoc($result)) {
        $name = array('name' => $row['ime']);
        $names[] = $name;
    }
    

    Once you fix that, the JSON you'll be sending will look like:

    [{"name": "Some name"}, {"name": "Another name"}, {"name": "Fred"}]
    

    In your Javascript, you're not accessing the name property. Change

    alert(name);
    

    to:

    alert(name.name);
    

    Or you could change the PHP so it just sends an array of strings instead of objects:

    while ($row = mysqli_fetch_assoc($result)) {
        $names[] = $row['ime'];
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探