【问题标题】:How can I replace the entire HTML of a page, or its body content, via an AJAX call's success callback?如何通过 AJAX 调用的成功回调替换页面的整个 HTML 或其正文内容?
【发布时间】:2017-01-15 14:58:55
【问题描述】:

我需要替换页面的整个 HTML 或其正文内容(而不是在现有内容中附加更多 html)。

接受的答案here 向我展示了如何返回数据,但将其添加到“body”并相当工作。这是我现在拥有的 jQuery:

<script>
    $(document).ready(function () {
        $("#btnGetData").click(function () {
            document.body.style.cursor = 'wait';
            $.ajax({
                type: 'GET',
                url: '@Url.RouteUrl(routeName : "QuadrantData", routeValues : new { httpRoute = true , unit = "ABUELOS", begdate = "2016-08-20", enddate = "2016-08-27"  })',
                contentType: 'text/plain',
                cache: false,
                xhrFields: {
                    withCredentials: false
                },
                success: function (returneddata) {
                    $("body").remove;
                    $("body").append($(returneddata));
                },
                error: function () {
                    console.log('hey, boo-boo!');
                }
            }); // ajax
            document.body.style.cursor = 'pointer';
        }); // button click
    }); // ready
</script>

...所以你可以看到我正在尝试首先删除正文中的 html,然后将返回的数据附加到正文中。

这个 REST 方法返回我想要的 html:

[System.Web.Http.HttpGet]
[System.Web.Http.Route("{unit}/{begdate}/{enddate}", Name = "QuadrantData")] 
public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate)
{
    _unit = unit;
    _beginDate = begdate;
    _endDate = enddate;
    string beginningHtml = GetBeginningHTML();
    string top10ItemsPurchasedHtml = GetTop10ItemsPurchasedHTML();
    string pricingExceptionsHtml = GetPricingExceptionsHTML();
    string forecastedSpendHtml = GetForecastedSpendHTML();
    string deliveryPerformanceHtml = GetDeliveryPerformanceHTML();
    string endingHtml = GetEndingHTML();
    String HtmlToDisplay = string.Format("{0}{1}{2}{3}{4}{5}",
        beginningHtml,
        top10ItemsPurchasedHtml,
        pricingExceptionsHtml,
        forecastedSpendHtml,
        deliveryPerformanceHtml,
        endingHtml);

    return new HttpResponseMessage()
    {
        Content = new StringContent(
            HtmlToDisplay,
            Encoding.UTF8,
            "text/html"
        )
    };
}

...但它附加了返回的 html 而不是替换它 - 原始正文 html 是完整的,并且返回的 html 出现在页面底部的下方。

如何替换而不是附加此 html?我尝试了 replacewith 和 replaceall,但这些对我不起作用。

【问题讨论】:

  • 我会在 body 上使用 the .html 函数而不是 .remove.append
  • $("body").remove; 什么?
  • 做 remove() 而不是 remove
  • 我期待一个后续问题,询问为什么 ajaxed in 页面中的 javascript 不起作用。

标签: javascript jquery asp.net-web-api replaceall replacewith


【解决方案1】:

remove() 将删除 body 元素(而不是仅仅清除它)。您可以使用它来匹配您正在尝试做的事情

$("body").empty();  
$("body").append($(returneddata));

但最好用

$("body").html(returneddata);

您可能还想查看 jQuery load() 函数,该函数将为您将 html 放入元素中。

【讨论】:

    【解决方案2】:

    由于您发送的内容类型为 text/html,因此您的代码应该可以正常工作。

    尝试像这样使用 Jquery.parseHTML 函数

    $("body").append($.parseHTML( returneddata )));
    

    你也有一行错误

    $("body").remove; 
    //it should be empty() since remove() remove all the content including body it self
    $("body").empty();
    

    链接:https://api.jquery.com/jquery.parsehtml/

    【讨论】:

      【解决方案3】:

      您只需使用$.get().html() 就可以做到这一点。由于语法错误(缺少括号)和.remove() 将完全删除正文,您的 .remove 调用将无法正常工作,因此您之后无法附加任何内容。您将不得不做类似的事情

      $(document).append($('<body>').append(returneddata));
      

      为了重新创建 BODY 节点并向其附加数据。

      此外,您应该将光标重置代码放在 .always 处理程序中,否则它将在 .get 或 .ajax 调用有机会执行之前设置并重置。 p>

      一般来说,

      console.log('this is executed first');
      $.get('...', function(){
          console.log('this should be executed third... sooner or later');
      });
      console.log('this is almost certainly executed second');
      

      所以你的代码可能是:

      $('#btnGetData').on('click', function() {
          $('body').css({ cursor: 'wait'});
          $.get(
                '@Url.RouteUrl(routeName : "QuadrantData", routeValues : new { httpRoute = true , unit = "ABUELOS", begdate = "2016-08-20", enddate = "2016-08-27"  })'
                  )
          .done(function(data) {
             // Replace 
             $('body').html(data);
          })
          .fail(function() {
             // Always plan for errors. Murphy rules.
             alert("error");
          })
          .always(function(){
              $('body').css({ cursor: 'pointer'});
          });
      })
      

      这是上面的fiddle

      【讨论】:

        【解决方案4】:

        虽然您已经使用了jquery,但您实际上并不需要为此使用它。为了用存储在变量newHTMLstring 中的html 替换body 元素的html,把它放在你的回调函数中:

        document.body.innerHTML = newHTMLstring;
        

        如果要先清除body元素的html,只需将.innerHTML设置为空字符串即可:

        document.body.innerHTML = '';
        

        这个 vanilla js 速度更快,适用于所有浏览器。

        【讨论】:

          【解决方案5】:

          您可以直接将您的 ajax 结果设置为 body,如下所示:

          $("body").html(ajaxresult);

          仍然无法正常工作,然后确保正确加载 jquery 并在文档上编写脚本,

          $(document).ready(function(){

          // 你的 AJAX 调用请求

          });

          【讨论】:

            猜你喜欢
            • 2010-10-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-07-15
            • 2012-12-08
            • 1970-01-01
            • 2014-10-10
            相关资源
            最近更新 更多