2010-11-23 5 views
1

다음과 같은 코드가 있습니다 :전체 HTML 페이지가 포함 된 Ajax 응답의 본문 태그 내에있는 내용 만 빼내려면 어떻게해야합니까?

$.ajax(
     { 
      url: rootPath + "Framework/GetPartial", 
      data: { partialName: partialName }, 
      type: "POST", 
      success: function (response) 
      { 
       $('#loading').hide(); 
       $('#partialContent').hide().html(response).fadeIn(); 
      }, 
      error: function (xhr, textStatus, errorThrown) 
      { 
       $('#loading').hide(); 
       $('#partialContent').hide().html('An error occurred. Details below:<br /><br />' + xhr.responseText).fadeIn(); 
      } 
     }); 

내가 신경 쓰는 것은 오류 처리 함수입니다. 서버에서 오류가 발생하면 자세한 디버그 정보가 포함 된 응답으로 html 페이지가 전송됩니다. 이 html 응답을 기존 페이지에로드하고 싶지만 응답에 <HTML>, <HEAD><BODY> 태그를 포함하면 전체 페이지의 서식이 손상됩니다. 다음 HTML 응답에서 JQuery를 사용하여 본문 태그의 내용을 어떻게 파싱 할 수 있습니까?

<html> 

    <head> 

     <title>The method or operation is not implemented.</title> 

     <style> 

     body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 

     p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} 

     b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} 

     H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } 

     H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } 

     pre {font-family:"Lucida Console";font-size: .9em} 

     .marker {font-weight: bold; color: black;text-decoration: none;} 

     .version {color: gray;} 

     .error {margin-bottom: 10px;} 

     .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } 

     </style> 

    </head> 



    <body bgcolor="white"> 



      <span><H1>Server Error in '/AlexAndNikki' Application.<hr width=100% size=1 color=silver></H1> 



      <h2> <i>The method or operation is not implemented.</i> </h2></span> 



      <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "> 



      <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 



      <br><br> 



      <b> Exception Details: </b>System.NotImplementedException: The method or operation is not implemented.<br><br> 



      <b>Source Error:</b> <br><br> 



      <table width=100% bgcolor="#ffffcc"> 

       <tr> 

        <td> 

         <code><pre> 



Line 19:   public PartialViewResult GetPartial(string partialName) 

Line 20:   { 

<font color=red>Line 21:    throw new NotImplementedException(); 

</font>Line 22:    //System.Threading.Thread.Sleep(3000); 

Line 23:    if (!ViewExists(partialName))</pre></code> 



        </td> 

       </tr> 

      </table> 



      <br> 



      <b> Source File: </b> C:\Users\alex.ford\Documents\Visual Studio 2010\Projects\AlexAndNikki\AlexAndNikki\Controllers\FrameworkController.cs<b> &nbsp;&nbsp; Line: </b> 21 

      <br><br> 



      <b>Stack Trace:</b> <br><br> 



      <table width=100% bgcolor="#ffffcc"> 

       <tr> 

        <td> 

         <code><pre> 



[NotImplementedException: The method or operation is not implemented.] 

    AlexAndNikki.Controllers.FrameworkController.GetPartial(String partialName) in C:\Users\alex.ford\Documents\Visual Studio 2010\Projects\AlexAndNikki\AlexAndNikki\Controllers\FrameworkController.cs:21 

    lambda_method(Closure , ControllerBase , Object[]) +127 

    System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +258 

    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39 

    System.Web.Mvc.&lt;&gt;c__DisplayClassd.&lt;InvokeActionMethodWithFilters&gt;b__a() +125 

    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640 

    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312 

    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709 

    System.Web.Mvc.Controller.ExecuteCore() +162 

    System.Web.Mvc.&lt;&gt;c__DisplayClass8.&lt;BeginProcessRequest&gt;b__4() +58 

    System.Web.Mvc.Async.&lt;&gt;c__DisplayClass1.&lt;MakeVoidDelegate&gt;b__0() +20 

    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453 

    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +371 

</pre></code> 



        </td> 

       </tr> 

      </table> 



      <br> 



      <hr width=100% size=1 color=silver> 



      <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1 



      </font> 



    </body> 

</html> 

<!-- 

[NotImplementedException]: The method or operation is not implemented. 

    at AlexAndNikki.Controllers.FrameworkController.GetPartial(String partialName) in C:\Users\alex.ford\Documents\Visual Studio 2010\Projects\AlexAndNikki\AlexAndNikki\Controllers\FrameworkController.cs:line 21 

    at lambda_method(Closure , ControllerBase , Object[]) 

    at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) 

    at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) 

    at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() 

    at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) 

    at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) 

    at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) 

    at System.Web.Mvc.Controller.ExecuteCore() 

    at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4() 

    at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0() 

    at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() 

    at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) 

--> 

편집 :

응답 문자열을 iframe에로드 할 수있는 방법이 있을까요? 가능하다면 이것은 훌륭 할 것입니다.

뭔가 :

$('#partialContent').html('<iframe>' + xhr.responseText + '</iframe>'); 

분명히이 코드를 시도하고 작동하지 않았지만 누군가가 iframe을 문제를 해결하는 방법을 알고 있을까요?

답변

2

나는 내 자신의 질문을 다시 해결했습니다 ........ 이것은 단지 두 번째 질문이며, 두 시간 동안 인터넷 검색을하면서 시간을 보냈습니다. 미안! 나는 누군가의 대답을 받아들이고 싶었다.

어쨌든 가장 쉬운 해결책은 html이 포함 된 응답 문자열을 iframe에 동적으로로드하는 것입니다. 당신이 좋은 똑똑한 'IE와 W3C 표준을 준수하는 그것의 실패를 설명 할 필요가 기억이 솔루션에 대한 필요가있는 경우

error: function (xhr, textStatus, errorThrown) 
      { 
       $('#loading').hide(); 
       $('#partialContent').html('<iframe style="width: 100%; height: 500px; border: solid 1px #000000;" id="errorFrame"></iframe>'); 
       var myFrame = $('#errorFrame')[0]; //top.frames['errorFrame']; 
       myFrame = myFrame.contentWindow || myFrame.contentDocument.document || myFrame.contentDocument; 
       myFrame.document.open(); 
       myFrame.document.write(xhr.responseText); 
       myFrame.document.close(); 
      } 

예를 들면 다음과 같습니다. contentWindow는 contentDocument에 해당하는 IE입니다. myFrame = myFrame.contentWindow || myFrame.contentDocument.document || myFrame.contentDocument;을 포함하는 한 괜찮을 것입니다. 모든 도움말 모두 http://67.2.141.90/AlexAndNikki/Framework/GenerateError

감사 : 여기

은 iframe 대응에로드 오류 페이지의 샘플입니다!

+2

+1 그게 효과가 있습니다. 참고로, 테스트가 끝나면 myFrame을 할당하는 코드를 줄일 수 있어야합니다. 할당 된 값은 동일합니다. 다음과 같이 논리 연산자 '||'연산자를 사용할 수 있습니다 :'myFrame = myFrame.contentWindow || myFrame.contentDocument.document || myFrame.contentDocument;'발견 한 첫 번째 것을 할당합니다. – user113716

+0

+1 바로 뒤로. – Chev

3

당신은 이런 식으로 작업을 수행 할 수 있습니다 추가 할 요소.

+0

나는 이것을 시도했다. 페이지에 인쇄 된 것은 모두'[object Object]'입니다. – Chev

+0

일부 브라우저에서는 실패합니다. Safari는 (예를 들어) ''의 내용을 제외한 모든 부분을 제거합니다. – user113716

+0

@Chevex - 대신이 시도해보십시오 :'var b = $ ('body', response) .contents(); $ ('# partialContent'). hide() .html (b.length? b : response) .fadeIn();'(죄송합니다. 여기서 사용하기 위해 전체 페이지를 반환하는 데 익숙하지 않습니다. –

1

var content = $ ('body') .html(); // 본문 내용을 제공합니다.

+0

질문을 이해할 수 없습니다. 그것은 스크립트가 실행되고있는 페이지의 본문을 제공합니다. 나는 아약스 요청의 XHR 응답 내에서 시체를 원한다. 'xhr.responseText' – Chev

+0

$ ('body', xhr.responseText) .html(); –

+0

숨겨진 iframe을 만들고 iframe의 html을 reposense 텍스트로 설정하는 또 다른 방법은 $ ('body', iframe) .html(); –

0

브라우저는 전체 HTML 페이지를 다르게 처리합니다. 정말로 원하는 내용 만 반환해야합니다.

가능하지 않은 경우 브라우저가 제거한 태그에 따라 다른 레벨에서 <body>을 찾습니다.

var $response = $(response); 

var $content = (($response.children('body').length) ? $response.children('body').contents() : 
       ($response.filter('body').length) ? $response.filter('body').contents() : 
       $response).not('style,title,script'); 

$('#partialContent').hide().html($content).fadeIn(); 

보장은 없지만 조금 도움이 될 수 있습니다.


편집 :는 오류 콜백을 처리하고 HTML을 연결하려는 통지를하지 않았다. 위의 내 대답은 연결에 [object Object]이됩니다.

partialContent에 응답을 추가 할 때를 제외하고는 위 코드를 사용하십시오.

var $response = $(response); 

var $content = (($response.children('body').length) ? $response.children('body').contents() : 
       ($response.filter('body').length) ? $response.filter('body').contents() : 
       $response).not('style,title,script'); 

$('#partialContent').hide().html('An error occurred. Details below:<br /><br />' + 
         $('<div>').append($content).html()).fadeIn(); 

편집 : 일부 브라우저는 또한 당신에게 <head>의 컨텐츠를 제공하기 때문에 추가 코드가 <title>, <style><script> 태그를 제거합니다.

+0

나는 내가 필요한 것을 돌려 주어야한다는 것을 안다. 성공할 경우에는이를 수행합니다. 실패시에만이 오류 응답이 다시 나타납니다. 마크 업을 페이지에 넣을 수 있습니다. – Chev

+0

@Chevex - 나는 충분히 자세히 보지 않았고 우리가'error :'콜백을 처리하고 있다는 것을 깨닫지 못했습니다. 1 분 후에 업데이트 할게. – user113716

+0

예, 오류 응답이 완전한 형식의 HTML 페이지로 돌아 오기 때문에 응답 문자열을 페이지에 놓으면 페이지의 많은 서식이 엉망입니다. 응답에서 본문 내용을 가져올 수 있다면 나는 페이지에 그 내용을 드롭 할 수 있으며 정상적으로 작동합니다. – Chev

관련 문제