簡體   English   中英

如何通過AJAX調用的成功回調替換頁面的整個HTML或正文內容?

[英]How can I replace the entire HTML of a page, or its body content, via an AJAX call's success callback?

我需要替換頁面的整個HTML或其主體內容(而不是將更多html附加到現有內容中)。

此處接受的答案向我展示了如何返回數據,但是將其添加到“ 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,但是這些對我來說不起作用。

remove()將刪除body元素(而不是清除它)。 您可以使用它來匹配您要嘗試的操作

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

但最好用

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

您可能還需要研究jQuery load()函數,該函數會將html放入您的元素中。

由於您發送內容類型為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/

您只需使用$.get().html()即可完成此操作。 由於語法錯誤(缺少括號),並且.remove()會完全刪除主體,因此您的.remove調用將無法工作,因此您之后無法再添加任何內容。 您將不得不做類似的事情

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

為了重新創建BODY節點並向其添加數據。

另外,您應該將游標重置代碼放入.always處理程序中,否則,它將在.get或.ajax調用有執行機會之前進行設置和重置

一般來說,

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'});
    });
})

這是上面的小提琴

盡管您已經使用了jquery ,但實際上並不需要使用它。 為了用存儲在變量newHTMLstring的html替換body元素的html,請將其放在回調函數中:

document.body.innerHTML = newHTMLstring;

如果要首先清除body元素的html,只需將.innerHTML設置為空字符串:

document.body.innerHTML = '';

這個普通的js速度更快,並且可以在每種瀏覽器中使用。

您可以將ajax結果直接設置為body,如下所示:

$(“ body”)。html(ajaxresult);

仍然無法正常工作,請確保正確加載了jquery並准備好在文檔中編寫腳本,

$(document).ready(function(){

//您的AJAX通話請求

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM