使用AJAX仅刷新一个div [英] Refresh only one div with AJAX

查看:81
本文介绍了使用AJAX仅刷新一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每五秒钟动态重新加载页面中的一个div.但是在我的响应中,我得到了整个页面的内容...我怎么只能获得指定div的内容?

I want to dynamically reload only one div in my page every five seconds. But in my response I get the content of the whole page... How can I get only the content of the specified div ?

<script>
function ajaxrefresh()
{
    var xmlhttp;

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            //Here i want only the content for the div from the response       
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
        else
        {
            //alert("state: "+xmlhttp.readyState)
            //alert("status: "+xmlhttp.status)
        }
    }

    xmlhttp.open("GET","http://${localHostAddress}:8080/adress",true);
    xmlhttp.send();

    var t=setTimeout(ajaxrefresh,5000);
}

window.load = ajaxrefresh();
</script>

推荐答案

由于无法使用Jquery,我认为最好的选择是响应ajax调用,仅从服务器端返回div内容.这样,您的响应大小将更小,因此也更快...

As you can not use Jquery, I think your best bet is in response to ajax call return only the div contents from server side. this way your response size will be smaller and hence faster too...

如果您无法通过以下代码更改请求使用的响应

if you can not change the response of request use below code

if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  //Here i want only the content for the div from the response  
  var mydiv= document.getElementById("myDiv"); 
  var doc=document.createElement("div");
  doc.innerHTML=xmlhttp.responseText;
  document.body.appendChild(doc); // Note append temp to document
 mydiv.innerHTML=doc.getElementById("theDivYouWant")
    .innerHTML;
  document.body.removeChild(doc);// Note remove temp from document

这篇关于使用AJAX仅刷新一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆