2016-09-07 1 views
-1

페이지의 전체 HTML 또는 본문 내용을 바꿔야합니다 (기존 내용에 더 많은 HTML을 추가하는 대신).AJAX 호출의 성공 콜백을 통해 페이지의 전체 HTML 또는 본문 내용을 어떻게 바꿀 수 있습니까?

대답이 here 인 경우 나에게 데이터를 반환하는 방법을 보여 주었지만 신체에 추가하면 일이 아닙니다. 이것은 내가 지금 가지고있는 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을 시도했지만, 이것들은 나에게 도움이되지 못했다.

+1

'.html] (http://api.jquery.com/html/) 함수를'.remove'와'.append' 대신' – bmceldowney

+1

'$ ("body") 대신 사용할 수 있습니다. 제거한다; "무엇? –

+0

제거 대신 remove()를 수행하십시오. –

답변

6

remove()은 (그냥 지우는 대신) 본문 요소를 제거합니다. 당신은 또한에 HTML을 배치 할 jQuery load() 기능을 조사 할 수 있습니다 당신은 당신이

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

을하려고 일치하려면이 옵션을 사용할 수 있지만

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

를 사용하는 것이 좋을 것이다 요소 (들).

0

콘텐츠 유형 text/html을 보내면 코드가 그대로 작동해야합니다. 이

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

같은 Jquery.parseHTML 기능을 사용하여

봅니다 또한 라인에서 실수가

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

링크 : https://api.jquery.com/jquery.parsehtml/

0

당신은 $.get().html()를 사용하여이 작업을 수행 할 수 있습니다 . 구문 오류 (괄호 누락)로 인해 .remove 호출이 작동하지 않았고 .remove()이 제거되어 나중에 본체를 제거 했으므로 이후에 아무 것도 추가 할 수 없었습니다. BODY 노드를 다시 작성하고 데이터를 추가하려면

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

과 같은 작업을 수행해야합니다.

또한 커서 재설정 코드를 .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'}); 
    }); 
}) 

이 위의 fiddle입니다.

0

이미 jquery을 사용하고 있지만이 용도로 사용할 필요는 없습니다. 변수 newHTMLstring에 저장된 HTML과 body 요소의 HTML을 대체하기 위해 콜백 함수에 넣고 :

document.body.innerHTML = newHTMLstring; 

을 먼저 본문 요소의 HTML을 삭제하려면, 단지에 .innerHTML 설정 빈 문자열 :

document.body.innerHTML = ''; 

이 바닐라 js는 더 빠르며 모든 브라우저에서 작동합니다.

0

직접 다음과 같이 몸에 당신의 아약스 결과를 설정할 수 있습니다

$ ("몸") HTML (ajaxresult을).

아직도이 준비 문서에 스크립트를 쓰기도 확실 JQuery와 제대로로드되어 있는지 확인 한 후 작동하지 않는

$ (문서) .ready (함수() {

// 당신의 AJAX 호출 요청

});

관련 문제