jQuery 单击时仅刷新一个 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23444691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:16:30  来源:igfitidea点击:

Refresh only a div on click

jqueryhtmlajax

提问by SergejV

After i click the button i want to refresh only <div class="wrap"> ... </div>With this window.location.reload()but i refresh whole page, so i need a ajax script that will refresh only that div.

单击按钮后,我只想 <div class="wrap"> ... </div>用这个 window.location.reload()刷新,但我刷新了整个页面,所以我需要一个仅刷新该 div 的 ajax 脚本。

<div class="wrap">

    // Content

    <div class="random_dil">
    <a class="button" onclick="window.location.reload()" href="#">Sljede?e pitanje</a>
    </div>

I tried this

我试过这个

<div id="mydiv"></div>
<a id="refresh">click</a>

<script>
$(function() {
  $("#refresh").click(function() {
     $("#mydiv").load("http://blah.com/page.php")
  })
})
</script>

But this again refresh whole site.

但这再次刷新整个网站。

回答by Surendheran

$.ajax({
    url: "http://blah.com/page.php",
    async: true
}).done(function(result) {
    $("#mydiv").html(result);
});

回答by Wayne

If you are saying that the entire page is being recreated inside the mydiv area, IE click is added into my div when you click it. It is because that is what page.php is providing, jquery can select only a portion of the page to do that change the third line of your scrip to.

如果您说整个页面都在 mydiv 区域内重新创建,则当您单击它时,IE 单击会添加到我的 div 中。这是因为这是 page.php 所提供的,jquery 只能选择页面的一部分来执行将脚本的第三行更改为。

$("#mydiv").load("http://blah.com/page.php #mydiv" );

In your 2nd "also tried" example.

在您的第二个“也尝试过”示例中。

回答by J.K

<script type="text/javascript">
function GetXmlHttpObject()
{
  if (window.XMLHttpRequest)
  {
    return new XMLHttpRequest();
  }
  if (window.ActiveXObject)
  {
    return new ActiveXObject("Microsoft.XMLHTTP");
  } 
  return null;
}

function ajax_function(url, postData, id)
{
xmlhttp=GetXmlHttpObject();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postData.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4)
    {
          document.getElementById(id).innerHTML=xmlhttp.responseText;                            
    }       
}                
    xmlhttp.send(postData);
 }

 function refreshDiv()
 {
var params = '';
var DivId  = 'wrap';
    var url    = 'http://blah.com/page.php';

ajax_function(url, params, DivId);
 }
 </script>

HTML

HTML

<div class="wrap">

// Content

<div class="random_dil">
<a class="button" onclick="refreshDiv()" href="#">Sljede?e pitanje</a>
</div>