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

时间:2010-06-06 18:14:38

标签: javascript jquery ajax

我有一个文本字段。当我在文本字段中键入内容时,我想将内容加载到下面的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>

2 个答案:

答案 0 :(得分:2)

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

使用jQuery的步骤如下:

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

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

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

答案 1 :(得分:0)

您可以这样做:

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

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

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