代码之家  ›  专栏  ›  技术社区  ›  arik

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

  •  3
  • arik  · 技术社区  · 14 年前

    我有一个文本字段。当我在非文本字段中键入内容时,我希望将内容加载到下面的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 回复  |  直到 14 年前
        1
  •  2
  •   acrosman    14 年前

    对于Ajax项目,从类似于 jQuery . 它将为您处理大量的工作。

    使用jquery,步骤如下:

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

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

      
      function finished(result) {
          $('#search_results').innerHTML(result);
      }
        2
  •  0
  •   lambacck    14 年前

    您可以执行以下操作:

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

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

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