I have this code that works ok when search button is pressed, but if one hits the enter button, it does not return any value from the database.
function showDetails(str){
if (str==""){
document.getElementById("searchDiv").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("searchDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_details.php?q="+st开发者_如何学运维r,true);
xmlhttp.send();
}
Here's how I'm using it in a separate page.
searchField
is a text input field in my form.
<button type="button" name="search" onclick="showDetails(searchField.value)">Search</button>
Like I said, it returns data from the server only when the search button is pressed but not when you hit the enter button on the computer keyboard. Is there any way I can make it respond to both?
That's because you haven't bound any event to the pressing of a key. Your event is very clearly labeled onclick
. So it responds to a click. Bind it to a keypress, check if that keypress is the enter key, and if so trigger the ajax request.
精彩评论