【发布时间】:2013-12-17 16:08:08
【问题描述】:
我正在尝试在 html、jQuery、ajax 和 php 中实现动态搜索功能。 问题是搜索功能仅在您输入 2-3 个字母时进行搜索。 例如:当按下字母“f”时,它应该返回数据库中包含字母“f”的每一行。返回 data 为空。(它应该返回 20 个值,我已经测试过查询) 现在它只在写“foo”时返回一个结果,也许是因为那是唯一有名字的行。这次返回的是xml结构:
<picture>
<picuser>CorrcetUser</picuser>
<picurl>CorrectURL</picurl>
<pictime>CorrectTime</pictime>
<picid>CorrectID</picid>
<comment>
<commenttime>Foo</commenttime>
<commentuser>Foo</commentuser>
<commenttext>Foo</commenttext>
</comment>
<description>
Foo bar
</description>
</picture>
下面是代码:
javascript 文件
$(document).ready(function() {
$(".search").keyup(function() {
var searchbox = $(this).val(); // get the string in the searchbox
var dataString = 'searchword=' + searchbox;
if (searchbox == '') {
} else {
$.ajax({
type : "POST",
url : "search.php",
data : dataString,
dataType : "xml",
async: false,
cache : false,
success : function(data, textStatus, jqXHR) {
//Data repsonse from server
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
}
});
});
这里是search.php
<?php
include ('dbconnect.inc.php');
if ($_POST) {
echo '<?xml version="1.0" standalone="no"?>';
$searchword = $_POST['searchword'];
$sql = "SELECT * FROM picture WHERE description LIKE :searchword";
$query = $dbh -> prepare($sql);
$query -> execute(array('searchword' => '%' . $searchword . '%'));
$nr=0;
$outputXML ="";
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
$outputUser = $row['userName'];
$outputPicURL = $row['picURL'];
$outputTime = date('Y-m-d H:i', $row['time']);
$outputString = $row['description'];
$outputPicID = $row['pictureID'];
$outputXML.= "<picture>
<picuser>$outputUser</picuser>
<picurl>$outputPicURL</picurl>
<pictime>$outputTime</pictime>
<picid>$outputPicID</picid>
<comment>
<commenttime>Foo</commenttime>
<commentuser>Foo</commentuser>
<commenttext>Bar</commenttext>
</comment>
<description>
Foo bar
</description>
</picture>";
}
echo $outputXML;
}
?>
我认为这是一个简单的解决方法,但在这里我被卡住了。 并且想知道为什么 data 是空的?
【问题讨论】:
-
async: false,为什么?? -
我认为从数据库中获取数据时这是一个好习惯,这是个坏主意吗?无论哪种方式都可以。
-
这是用于 Intranet 还是 Internet 站点?这可能是个坏主意,因为这是等待发生的 DOS 攻击。想象一下,一个用户来到该站点并开始触发您的搜索框的 keyup 事件,一遍又一遍地向您的服务器发送大量请求。然后想象多个用户做同样的事情。如果他们使用的是标准浏览器(chrome、IE、firefox 等),那么可以发出的请求数量是有限的,但如果他们使用的是专为此类攻击而设计的自定义浏览器,那么您将非常容易通过 DOS 攻击关闭服务器的方法
-
这是我在 MAMP 上本地运行的一个学校项目。我还没有真正考虑过安全方面。不过,我很高兴你指出了这一点。
标签: javascript php jquery ajax xml