Is it possible to create a searchbox for my site using javascript?
I'd like to create a search box on the home page of my site that would be able to search the entire site. I know 开发者_JAVA百科it's a very general question but I'd be very happy with just a general conceptual answer is there anyway to do this?
You can't really do this using Javascript. You'll have to use some sort of server-side language that has access to your database. Alternately, you can use something like Google Custom Search Engine to provide searching capabilities.
Once you start wanting users to be able to search your site, it implies that your site is larger than just a few simple HTML pages. Have you thought about using something like Drupal, Joomla!, Wikimedia, or some other CMS? Most of those have search capability built in (one way or another).
People are going to tell you no. They're mostly right that his probably isn't the best way to do this.
But depending on your site, it may be technically incorrect to say this can't be done with JavaScript. If all the documents you want to be searchable have a unique URL that's used throughout the site, and if their graph is connected, I think you could write a spider in JavaScript that begins indexing all these pages as soon as a user hits your site. It'd do what any other spider did: look for links on the current page, request the documents behind them (using XMLHTTPRequest or a frame or popup window of some kind), process the document and index keywords based on some scheme, and store the results (possibly in a a cookie).
Of course, duplicating all this work for each visitor doesn't make a lot of sense, which is why the other people telling you no are mostly right. But it's theoretically possible.
This is would involve much more than just Javascript and depends on a number of different variables. Often, sites are built on a MySQL (or similar) database. If this is true in your case you may want to use some PHP to get into it and search through each record. Here's an example using PHP and MySQL.
For the form, something like this will work:
HTML
<form action="?" method="get">
<input type="text" id="search" name="search" />
<input type="submit" name="submit" id="submit" value="Search" />
</form>
Then you'll need to use some PHP, assuming you want to search the title and body of one table of blog posts:
$search_terms = mysql_real_escape_string($_GET['search']);
$resc = mysql_query("SELECT * FROM blog_posts WHERE title LIKE '%".$search_terms."%' OR body LIKE '%".$search_terms."%'");
$posts = mysql_fetch_assoc($resc);
now $posts
is an array containing all of your posts which match the search terms in their title or body.
NOTE: In order to search for text
type MySQL fields you will need to make the field a FULLTEXT
index.
Check this link out for more info: http://devzone.zend.com/article/1304
This is a VERY SIMPLE solution, but it will get you on the right track.
精彩评论