2016-03-14 55 views
0

我無法做出一個Ajax函數的調用,如下所示(的index.php):無法進行調用Ajax和PHP

<script type="text/javascript"> 

$('.show_more').on('click',function (e){ 
    $.ajax({ 
     type:'POST', 
     url:'gallery_controller.php', 
     success:function(html){ 
      $('.content').append(html); 
     } 
    }); 
}); 

我按一下按鈕就在這裏(的index.php):

<form action="" method="post">     
<button type="submit" class="show_more" name="next">Next</button> 
</form> 

這是我的PHP腳本(gallery_controller.php):

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = ""; 

$conn = new mysqli($servername, $username, $password, "dbgallery"); 

if ($conn->connect_error) { 
die("Connection failed: " . $conn->connect_error); 
} 

$result = $conn->query("SELECT imagefile FROM tbl_images ORDER BY id DESC LIMIT 10 OFFSET 0"); 

while($row = $result->fetch_assoc()) { 

echo '<h1>'.$row["imagefile"].'</h1><hr />'; 

} 
?> 

它似乎什麼都不做,我試了幾件事,似乎沒有任何工作..即時通訊想知道如果Ajax甚至可以在我的服務器上工作..我是一個完整的noob。

+0

你將它封裝在一個表單中,正在發送ajax調用,但表單在完成並刷新頁面之前進行了很多評估。嘗試在函數打開後添加'e.preventDefault();'函數返回false;或者您可以將'type =「submit」'更改爲'type =「button」',這樣按下按鈕就不會' t提交表格 –

+0

通常,使用瀏覽器開發控制檯執行此類編程任務非常重要。它可以讓你看到瀏覽器實際上做了什麼。如果沒有這個,你就會盲目的,這從來不是一個好主意:-) – arkascha

回答

0

請檢查以下完整的代碼。我認爲「e.preventDefault();」在您的代碼中缺少。

<html> 
    <head> 
     <title>Test</title> 
    </head> 
    <body> 

<form action="" method="post">     
<button type="submit" class="show_more" name="next">Next</button> 
</form> 
<div class="content"> 

</div> 

<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> 
<script> 
$('.show_more').on('click',function (e){ 
    e.preventDefault(); 
    $.ajax({ 
     type:'POST', 
     url:'gallery_controller.php', 
     success:function(html){ 
      $('.content').append(html); 
     } 
    }); 
}); 
</script>  

    </body> 
</html> 
1

您是否需要該按鈕的表單? 如果您將按鈕封裝到W3C有效性問題的表單中,那麼您可以簡單地將您的按鈕類型屬性從type =「submit」更改爲type =「button」。