开发者

How to make up a search box?

How to make up a form that is going to be a search box and work only via Ajax? That is:

1) What to put as the form's action value? (action="what")

开发者_如何学C

2) How to submit it so that nothing else happenes except for calling the JavaScript function?


You can do something like:

<input id="search" /> <input type="button" onclick="doSearch()" />
<div id="results"></div>

dosearch will be something like

function doSearch()
    {
    var s = document.getElementById("search");
    // Substitute this line with whatever code you use to do an AJAX call
    // Essentially call a serverside page by passing the search keyword and
    // call onReturn afterwards 
    doAJAXCall("searchpage.php?q="+s.value, onReturn);
    }

searchpage.php will search the DB as needed and then return, for instance, a JSON string (e.g. by storing the results in an array and using json_encode) or XML or even straight HTML

Finally, the onReturn function will go through the results and print them for instance in a list, like this:

 function onReturn(results)
     {
     // decode your results variable here in the appropriate way
     // e.g. into a JSON object 
     var d = document.getElementById("results");

     var res = "<ul>";

     for (var i=0; i<results.lenght; i++)
         res = res + "<li>"+i.text+"</li>";

     res = res + "</li>";
     d.innerHTML = res; 
     }


Use a framework like jQuery. It has facilities to hook forms and turn them into AJAX. Check out the jQuery Forms plugin.


  1. form is irrelevant for this. form is just a container for the other form elements. You can have whatever action you want for it (GET / POST, whatever), won't matter.
  2. attach an event handler to the search button click or keydown event for the textbox and check for Enter key and route the value of the textbox to an AJAX call using xmlhttp object. I am sure you can find the detail on how to do Ajax using xmlHttpRequest object somewhere on the web :)... or... well, you can use jQuery, lol.


I think it works well this way:

<form method="post" onsubmit="theFunction(this); return false;">
    <input type="text" value="" class="address_bar" />
</form>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜