Use AJAX to load webpage content into DIV
I have a text field. When I type something into than text field, I want to load stuff into the DIV below. That's my code equivalent:
<input type="text" onkeyup="/* I am not sure how it's done, but I'll just write: */ document.getElementById('search_results').innerHTML = getContents('search.php?query='+this.value);" /><br/>
<div id="search_results"></div>
Hope you can help. Thanks in advance!
EDIT: I would appreciate it if the solution did not involve using jQuery - as long as it's possible.
ANSWER: How I'm doing it:
<input type="text" onkeyup="loadSearchResults(this.value)" /><br/>
<div id="search_results"></div>
<script>
function loadSearchResults(query){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Mi开发者_开发技巧crosoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("search_results").innerHTML=xmlhttp.responseText;
}else if(xmlhttp.readyState>=1 && xmlhttp.status==200){
// show the ajax loader or stuff like that...
}
}
xmlhttp.open("GET","search.php?search="+query,true);
xmlhttp.send();
}
</script>
For AJAX projects start with a library like jQuery. It will handle a great deal of the work for you.
Using jQuery the steps would be something like:
Use the ajax command to retrieve the data from your server.
$.ajax({ url: 'search.php', data: "query=search_terms", success: finished(data));
update the div on result using a function like:
function finished(result) { $('#search_results').innerHTML(result); }
You would do something like:
$("#inputid").keyup(function(evt) {
$("#search_results").load("/getresults.php", {queryparam: evt.target.value});
});
Of course, it does end up being more complicated than that. You probably don't want to send a request to the server on every key press.What happens if the server takes a long time to respond? Should you provide some indication that a request to the server is being made?
If you use jQueryUI, you can use the autocomplete widget, which might get you closer to then end result you want.
精彩评论