我有一个愚蠢的问题。一个jQuery.ajax
请求以字符串形式返回给我一个完整的 HTML 文本。如果服务器出现错误,我会收到此类响应。服务器给我一个错误描述,我想把它放在当前页面的相应位置。
那么现在的问题是:我有一个包含完整 HTML 文档的字符串(这不是 XML!!!请参阅里面的 <hr>
元素)。例如,我只需要 BODY 部分作为 jQuery 对象。然后我可以将它附加到我页面的相应部分。
这是我需要解析的字符串示例:
<html>
<head>
<title>The resource cannot be found.</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}
// ...
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>The resource cannot be found.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>HTTP 404. The resource you are looking for ...bla bla....
<br><br>
<b> Requested URL: </b>/ImportBPImagesInfos/Repository.svc/GetFullProfilimageSw<br><br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
</font>
</body>
</html>
<!--
[HttpException]: A public action method '....
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
最佳答案
以及必备的非 jQuery 答案:
var bodyHtml = /<body.*?>([\s\S]*)<\/body>/.exec(entirePageHTML)[1];
这将只返回 body 标签内的内容。
UPDATE 这接受 body 标签上设置的属性
关于javascript - 如何从 html 中获取作为字符串的 <body> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2857126/