2017-05-25 97 views
0

我想从我的数据库使用ajax和php获取数据,但每当我尝试获取数据时,都会收到ajax错误消息。这里是我的代码:PHP将数据发送回AJAX

HTML

这里是我的代码,我请求PHP文件。

<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

这是我的PHP文件

<?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); 
+3

有什么错误? –

回答

2

你在你的PHP无限循环。你只是取一行,然后遍历同一行。既然你永远不会改变循环中的$row,它永远不会结束。它应该是:

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

一旦你解决这个问题,你会被发送JSON的样子:

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

在JavaScript,你不访问name财产。更改

alert(name); 

到:

alert(name.name); 

或者你可以改变PHP所以它只是将字符串而非对象的数组:

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

谢谢,这使问题消失 – byteMe