繁体   English   中英

如何只提取包含整个HTML页面的Ajax响应的body标记内的内容?

[英]How do I pull out only the content within the body tag of an ajax response that contains an entire HTML page?

我有以下代码:

$.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解析出body标记中的内容?

<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解决问题?

您可以这样做:

$('#partialContent').hide().html($('body',response).contents()).fadeIn();

这是下面的.empty().append()的快捷方式,但是主要部分是$('body',response) ,它在$('body',response)中寻找<body>元素,然后将其内容作为要包含的元素。附加。

我解决了自己的问题。 这只是我的第二个问题,而且两次我都花了几个小时进行谷歌搜索并自己想出了答案。 对不起大家! 我真的很想接受别人的回答。

无论如何,我发现最简单的解决方案是将包含html的响应字符串动态加载到iframe中。 这是一个例子:

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

如果您需要此解决方案,请记住,您必须考虑好的IE及其不遵循W3C标准的情况。 contentWindow与IE等效于contentDocument。 只要包含myFrame = myFrame.contentWindow || myFrame.contentDocument.document || myFrame.contentDocument; myFrame = myFrame.contentWindow || myFrame.contentDocument.document || myFrame.contentDocument; 你会没事的。

以下是加载到iframe中的错误页面的示例: http : //67.2.141.90/AlexAndNikki/Framework/GenerateError

谢谢各位的帮助!

var content = $('body')。html(); //为您提供身体的内容

浏览器处理完整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>标记。

暂无
暂无

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

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