Ajax Live Search - 获取2个字段而不是1个

时间:2011-02-07 08:09:00

标签: php jquery mysql ajax search

我有一个小问题,我想要一个实时搜索,它返回一个POST_TITLE和一个POST_ID。标题是供人们看到的,但我的主要原因是我希望POST_ID与它一起使用。

有人可以帮助我,我发布了下面的代码......

   <script>
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
    }
}

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
    if (searchReq.readyState == 4 || searchReq.readyState == 0) {
        var str = escape(document.getElementById('txtSearch').value);
        searchReq.open("GET", '/wp-content/themes/twentyten/livesearch.php?search=' + str, true);
        searchReq.onreadystatechange = handleSearchSuggest;
        searchReq.send(null);
    }        
}

//Called when the AJAX response is returned.
function handleSearchSuggest() {
    if (searchReq.readyState == 4) {


           var sx = document.getElementById('restaurantid')
        sx.innerHTML = '';

        var ss = document.getElementById('search_suggest')
        ss.innerHTML = '';
        var str = searchReq.responseText.split("\n");
        for(i=0; i < str.length - 1; i++) {
            //Build our element string.  This is cleaner using the DOM, but
            //IE doesn't support dynamically added attributes.
            var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
            suggest += 'onmouseout="javascript:suggestOut(this);" ';
            suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
            suggest += 'class="suggest_link">' + str[i] + '</div>';
            ss.innerHTML += suggest;
            ss
        }
    }
}

//Mouse over function
function suggestOver(div_value) {
    div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
    div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
    document.getElementById('txtSearch').value = value;
    document.getElementById('restaurantid').value = value;
    document.getElementById('search_suggest').innerHTML = '';
}
</script>


<form id="frmSearch" action="">
    <input type="text" id="restaurantid" name="restaurantid" style="display: none;" />
                    <input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria" onkeyup="searchSuggest();" autocomplete="off" />
                    <input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" />
                    <div id="search_suggest"></div>
                </form>
</code>

livesearch.php - THE AJAX PAGE

<code>
<?php

$con = mysql_connect('x', 'x', 'x);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("xx", $con);
if (isset($_GET['search']) && $_GET['search'] != '') {
    //Add slashes to any quotes to avoid SQL problems.
    $search = addslashes($_GET['search']);
    //Get every page title for the site.
    $suggest_query = mysql_query('SELECT * FROM `mrr_posts` WHERE `post_title` LIKE \'%'.$search.'%\' AND `post_status` LIKE \'publish\' LIMIT 0, 30') or trigger_error("Query: $suggest_query\n<br />MySQL Error: " .mysql_error());            
    while ($suggest = mysql_fetch_array($suggest_query, MYSQL_ASSOC)) {    
    //while($suggest = db_fetch_array($suggest_query)) {
        //Return each page title seperated by a newline.
        echo $suggest['post_title'] . "\n";
    }
}





mysql_close($con);
?>

3 个答案:

答案 0 :(得分:1)

我注意到在上面的讨论中你现在正在返回JSON,并从客户端解析它。我注意到你用jQuery标记了你的问题,所以我猜你正在使用它。这不是你的问题的答案,但这里有一些jQuery编码的技巧,这将有助于简化你的代码。

  • 而不是直接使用XMLHttpRequest对象进行ajax调用,只需使用$ .get(url,successFunction)
  • 而不是使用getElementById('some-id'),使用$('#some-id'),然后执行清空内部html之类的操作,你可以执行$('#some-id')。 HTML( '')。使用jQuery元素而不是HTMLElement,您还可以以跨浏览器兼容的方式操作DOM:http://api.jquery.com/category/manipulation/
  • 而不是将您的javascript构建到您的HTML(所有那些onmouseover和onmouseout处理程序),使用$('div.suggest_link')来选择页面上具有“suggest_link”类的所有div。然后,附加一个实时事件处理程序,它将处理动态生成的html,如下所示:$('div.suggest_link')。live('mouseover',handleMouseOverForSuggestLink)。您可以在jQuery的页面上阅读更多相关信息:http://api.jquery.com/live/

所有这些建议都适用于现代浏览器,并有助于减少大量代码。祝你好运!

答案 1 :(得分:0)

您应该在JSON(或XML,但JSON更容易)中从服务器返回数据,然后在Javascript中解析它。向用户显示标题,id为自己保留。

答案 2 :(得分:0)

一般来说,xajax可能会简化事情。看看我的答案:

how to assign a javascript variable to a smarty variable