2014-10-28 55 views
1

我的情況如下,我有一個表單輸入在Jquery Mobile頁面,我提交表單沒有表單按鈕。我需要從PHP返回的結果(它在JSON中)返回到HTML。但在我按下回車鍵提交搜索時,它會鏈接到php頁面,並返回結果並停留在那裏,而不是返回到html頁面。 感謝您的時間!發送HTML表單輸入,然後卡在PHP頁面

代碼:

$("#searchform").submit(function(event) { 
    $.ajax({ 
     type: "GET", 
     url: "http://test.com/App/searchtest.php", 
     dataType:'json', 
     success: function(data){ 
      console.log(data); 
      $("#content").append(data); 
     } 
    }) 
}); 
<form id="searchform" name="searchform" method="post" 
     action="http://www.test.com/App/searchtest.php" data-ajax="false"> 
    <input type="search" id="searchinput" name="searchterm" 
     value="" data-mini="true" placeholder="Where?"/> 
</form> 
<?php 
ini_set('display_errors', 1); error_reporting(E_ALL); 

include 'connect.php'; 

$search = ($_POST['searchterm']); 
$keywords = explode (" ", $search); 
$columns = array("country","name"); 
$andParts = array(); 

foreach ($keywords AS $keyword){ 
    $orParts = array(); 
    foreach($columns AS $column){ 
     $orParts[] = $column . " LIKE '%" . ($keyword) . "%'"; 
    } 
    $andParts[]= "(" . implode($orParts, " OR ") . ")"; 
} 

$and = implode ($andParts, " AND "); 

$sql = "SELECT * FROM Listing WHERE $and "; 

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

$output = array(); 

// fetch your results 
while($row = mysqli_fetch_assoc($result)) { 
    // add result row to your output's next index 
    $output[] = $row; 
} 

// echo the json encoded object 
echo json_encode($output); 

?> 
+0

奔,請提供'php'讓我們來看看。此外,請檢查您的瀏覽器控制檯「網絡」選項卡以查看來自服務器的響應。它很可能會告訴你發生了什麼 – Growler 2014-10-28 18:40:57

+0

你在控制檯中看到了什麼(如果有的話)。還包括一些'php'代碼 – 2014-10-28 18:42:41

+0

好吧,但PHP返回的JSON沒有問題。但我在編輯中更新了它。 – Ben 2014-10-28 18:43:05

回答

-1

本與您的代碼的問題是,你要發送的Ajax請求,並在同一時間,這意味着連接到PHP頁面提交表單,重新加載頁面,從而取消ajax成功處理程序。
爲避免出現這種情況,您應該在發送事件處理程序結束時或致電event.preventDefault時,返回假,以防止表單提交。
我希望這有助於:

$("#searchform").submit(function(event) { 
    $.ajax({ 
     type: "GET", 
     url: "http://test.com/App/searchtest.php", 
     dataType:'json', 
     success: function(data){ 
      console.log(data); 
      $("#content").append(data); 
     } 
    }) 
    return false; 
}); 
+0

@ rm-vanda:這就是爲什麼我說「或調用event.preventDefault」。我只提供了兩種方法可以防止提交的默認行爲 – oskr 2014-10-28 20:15:45

0

現代的方式做oskr表明什麼是使用.preventDefault() -

$("#searchform").submit(function(event) { 
    event.preventDefault(); 

    $.ajax({ 
     type: "GET", 
     url: "http://test.com/App/searchtest.php", 
     dataType:'json', 
     success: function(data){ 
      console.log(data); 
      $("#content").append(data); 
     } 
    }) 
});