使用AJAX将网页内容加载到DIV中

我有一个文本字段。 当我在文本字段中键入内容时,我想将内容加载到下面的DIV中。 那是我的代码等价物:


希望你能帮忙。 提前致谢!

编辑:如果解决方案不涉及使用jQuery,我将不胜感激 – 只要它是可能的。

答案:我是怎么做到的:

 
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("Microsoft.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(); }

对于AJAX项目,请从像jQuery这样的库开始。 它将为您处理大量工作。

使用jQuery的步骤如下:

  1. 使用ajax命令从服务器检索数据。

     $.ajax({ url: 'search.php', data: "query=search_terms", success: finished(data)); 
  2. 使用如下函数更新结果div:

     function finished(result) { $('#search_results').innerHTML(result); } 

你会做的事情如下:

 $("#inputid").keyup(function(evt) { $("#search_results").load("/getresults.php", {queryparam: evt.target.value}); }); 

当然,它最终会变得更加复杂。 您可能不希望在每次按键时向服务器发送请求。如果服务器需要很长时间才能响应,会发生什么? 您是否应该提供一些指示,表明正在向服务器发出请求?

如果您使用jQueryUI,则可以使用自动完成小部件 ,这可能会让您更接近您想要的最终结果。