简体   繁体   English

如何通过AJAX调用的成功回调替换页面的整个HTML或正文内容?

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

I need to replace the entire HTML of a page, or its body content (rather than append more html to the existing content). 我需要替换页面的整个HTML或其主体内容(而不是将更多html附加到现有内容中)。

The accepted answer here showed me how to return data, but adding it to "body" doesn't quite work. 此处接受的答案向我展示了如何返回数据,但是将其添加到“ body”中并不太起作用。 This is the jQuery I have now: 这是我现在拥有的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>

...So you can see I'm trying to first remove the html in the body, and then append the returned data to the body. ...所以您可以看到我正在尝试先删除正文中的html,然后将返回的数据附加到正文中。

This REST method returns the html I want: 此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"
        )
    };
}

...but it appends the returned html rather than replacing it - the original body html is intact, and the returned html appears below it at the bottom of the page. ...但是它将附加返回的html而不是替换它-原始正文html是完整的,并且返回的html出现在页面底部。

How can I replace, rather than append, this html? 我如何替换而不是附加该html? I tried replacewith and replaceall, but these didn't work for me. 我尝试了replacewith和replaceall,但是这些对我来说不起作用。

remove() will remove the body element (instead of just clearing it out). remove()将删除body元素(而不是清除它)。 You can use this to match what you are trying to do 您可以使用它来匹配您要尝试的操作

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

but it would be better to use 但最好用

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

You also may want to look into the jQuery load() function which will place the html into the element(s) for you. 您可能还需要研究jQuery load()函数,该函数会将html放入您的元素中。

Since you sending content type text/html your code should work as it is. 由于您发送内容类型为text / html,因此您的代码应该可以正常工作。

Try using Jquery.parseHTML function like this 尝试像这样使用Jquery.parseHTML函数

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

Also you have a mistake in line 你也错了

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

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

You can do this by just using $.get() and .html() . 您只需使用$.get().html()即可完成此操作。 Your .remove call would not have worked because of a syntax error (missing parentheses) and because .remove() would have removed the body altogether, so that you could not have appended anything to it afterwards. 由于语法错误(缺少括号),并且.remove()会完全删除主体,因此您的.remove调用将无法工作,因此您之后无法再添加任何内容。 You would have had to do something like 您将不得不做类似的事情

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

in order to re-create the BODY node and appending data to it. 为了重新创建BODY节点并向其添加数据。

Also, you should put the cursor reset code in the .always handler, though, otherwise it will be set and reset before the .get or .ajax call has a chance of executing. 另外,您应该将游标重置代码放入.always处理程序中,否则,它将在.get或.ajax调用有执行机会之前进行设置和重置

In general, 一般来说,

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

So your code could be: 因此,您的代码可能是:

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

This is a fiddle of the above. 这是上面的小提琴

Although you already use jquery , you don't really need to use it for this. 尽管您已经使用了jquery ,但实际上并不需要使用它。 In order to replace the html of the body element with html stored in the variable newHTMLstring , put this in your callback function: 为了用存储在变量newHTMLstring的html替换body元素的html,请将其放在回调函数中:

document.body.innerHTML = newHTMLstring;

If you want to clear the html of the body element first, just set .innerHTML to an empty string: 如果要首先清除body元素的html,只需将.innerHTML设置为空字符串:

document.body.innerHTML = '';

This vanilla js is faster and works in every browser. 这个普通的js速度更快,并且可以在每种浏览器中使用。

You can directly set your ajax result to body as below: 您可以将ajax结果直接设置为body,如下所示:

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

Still it is not working then make sure jquery is loaded properly and also write your script on document ready, 仍然无法正常工作,请确保正确加载了jquery并准备好在文档中编写脚本,

$(document).ready(function(){ $(document).ready(function(){

// Your AJAX call request //您的AJAX通话请求

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM