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

Javascript 使用AJAX将网页内容加载到DIV中,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有一个文本字段。当我在than文本字段中键入内容时,我想将内容加载到下面的DIV中。这是我的代码等价物: <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);" /><

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

<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>

希望你能帮忙。提前谢谢

编辑:如果解决方案不涉及使用jQuery,我将不胜感激——只要有可能

回答:我是如何做到的:

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

}
</script>

函数loadSearchResults(查询){ if(window.XMLHttpRequest){//IE7+、Firefox、Chrome、Opera、Safari的代码 var xmlhttp=new XMLHttpRequest(); }else{//IE6、IE5的代码 var xmlhttp=newActivexObject(“Microsoft.xmlhttp”); } xmlhttp.onreadystatechange=函数(){ if(xmlhttp.readyState==4&&xmlhttp.status==200){ document.getElementById(“搜索结果”).innerHTML=xmlhttp.responseText; }else if(xmlhttp.readyState>=1&&xmlhttp.status==200){ //显示ajax加载程序或类似的东西。。。 } } open(“GET”、“search.php?search=“+query,true”); xmlhttp.send(); }
对于AJAX项目,从库开始,例如。它将为你们处理大量的工作

使用jQuery,步骤如下:

  • 使用从服务器检索数据

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

    
    功能完成(结果){
    $(“#搜索结果”).innerHTML(结果);
    }


  • 您可以执行以下操作:

    $("#inputid").keyup(function(evt) {
        $("#search_results").load("/getresults.php", {queryparam: evt.target.value});
    });
    
    当然,它最终要比这复杂得多。您可能不希望在每次按键时都向服务器发送请求。如果服务器需要很长时间才能响应,会发生什么情况?您是否应该提供一些向服务器发出请求的指示


    如果您使用jQueryUI,您可以使用,这可能会使您更接近您想要的最终结果。

    OK。现在,如果我安装jQuery,我该怎么做呢?我添加了一些详细信息来扩展答案,详细信息因安装而异,但这应该会让您找到一个高效的方向。这看起来很棒!谢谢我会试试看。尽管如此,我还是很想知道如何将jqueryajax命令与JavaScript结合使用。这是关于XMLHTTPRequest之类的东西。我对AJAX非常缺乏经验,但我真的需要知道。提前谢谢!jQuery处理与为您执行XMLHTTPRequests相关的跨浏览器问题。可能值得努力找到一个描述如何直接执行请求的教程(如),但我会坚持使用流行的库,以供实际生产使用。与此同时,我访问了W3学校,并成功地管理了!
    $("#inputid").keyup(function(evt) {
        $("#search_results").load("/getresults.php", {queryparam: evt.target.value});
    });