【问题标题】:Web page becomes unresponsive after ajax callajax 调用后网页无响应
【发布时间】:2016-01-18 19:11:33
【问题描述】:

我有一个网页,我在其中从服务器获取一些数据。我使用 servlet 从服务器获取数据。我需要每 5 秒 inerval 获取数据。我在脚本中使用了 ajax 调用,但是在几次调用之后,网页变得没有响应。我发现一件事在这里我已经再次替换了整个 html 页面,我怎样才能将特定的 div 与输出的 html 内容(这里 page_html)分开。我只想替换 div

setInterval("update_content();", 5000);

function update_content(){
    $.ajax({
        url: "url", // post it back to itself - use relative path or consistent www. or non-www. to avoid cross domain security issues
        type: "POST",
        async: true,
        cache: false, // be sure not to cache results
    })
    .done(function( page_html ) {
        var newDoc = document.open("text/html", "replace");
        newDoc.write(page_html);
        newDoc.close();         
    });       
}    

【问题讨论】:

  • 使用setInterval(update_content, 5000); 而不是setInterval("update_content();", 5000);
  • 控制台有错误吗?
  • 这很奇怪。你能在 JSFIddle 上发布最小的可重现示例吗?
  • 异步调用有什么问题吗?
  • @YeldarKurmangaliyev:嘿,我找到了问题,你能帮我多一点吗,请查看编辑...

标签: javascript jquery html ajax web-applications


【解决方案1】:

如何从输出的 html 内容(此处为 page_html)中分离出特定的 div。我只想替换 div

您可以使用 jQuery html() 方法简单地更改 div 的内容。

<div id="yourDivId">
</div>

JS:

function update_content(){
    $.ajax({
        url: "url", // post it back to itself - use relative path or consistent www. or non-www. to avoid cross domain security issues
        type: "POST",
        async: true,
        cache: false, // be sure not to cache results
    })
    .done(function(page_html) {
        $("#yourDivId").html(page_html);
    });       
}    

此方法将使用 AJAX 加载 HTML,然后将 #yourDivId 的 HTML 内容替换为加载的数据。这就是 AJAX 通常用于的用途。

【讨论】:

  • 我有一个响应 html ,根据这个如果我有一个 div 并且我正在进行 ajax 调用,它会将响应数据加载到我的 div 对吗?
  • 我想从我的响应中加载一个特定的 div 到我的 div id ,这里整个响应将加载到我的 div id 对吗?
  • @JamesHoffman 是的,整个响应将替换目标 HTML。为了使其成为 AJAX 样式,您只需返回 div 内容作为响应,而不是整个页面。
  • 这里如何只返回 div 内容?我看到了一个使用 filter() 和 find() 的方法,但都没有正常工作,你有什么建议吗?
猜你喜欢
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多