2014-10-28 53 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); 
     } 
    }) 
});