问题描述
|
我要执行以下操作。
$(\"a\").click(function (event) {
event.preventDefault();
$.get($(this).attr(\"href\"),function(data) {
$(\"html\").html(data);
});
});
我想要所有超链接的行为进行ajax调用并检索html。
不幸的是,您不能简单地用ajax响应中收到的html替换当前的html。
如何仅获取ajax响应的<body> </body>
标记内的内容,以便仅替换现有html中正文的内容。
编辑:<body>
开头的标签并不总是<body>
,有时可能会有一个类,例如
<body class=\"class1 class2\">
解决方法
如果我对您的理解正确,请使用正则表达式在body标签之间获取内容。
$.get($(this).attr(\"href\"),function(data) {
var body=data.replace(/^.*?<body>(.*?)<\\/body>.*?$/s,\"$1\");
$(\"body\").html(body);
});
编辑
根据您在下面的评论,这是一个更新,以匹配任何body标签,无论其属性如何:
$.get($(this).attr(\"href\"),function(data) {
var body=data.replace(/^.*?<body[^>]*>(.*?)<\\/body>.*?$/i,\"$1\");
$(\"body\").html(body);
});
正则表达式为:
^ match starting at beginning of string
.*? ignore zero or more characters (non-greedy)
<body[^>]*> match literal \'<body\'
followed by zero or more chars other than \'>\'
followed by literal \'>\'
( start capture
.*? zero or more characters (non-greedy)
) end capture
<\\/body> match literal \'</body>\'
.*? ignore zero or more characters (non-greedy)
$ to end of string
添加\'i \'开关以匹配大写和小写。
并且请忽略我对\'\'开关的评论,在JavaScript中,所有RegExp默认情况下已为单行,要匹配多行模式,请添加\'m \'。 (该死的Perl,在我写JavaScript时干扰我!:-)
, 我不想弄乱正则表达式。相反,我创建了一个隐藏的<iframe>
,将内容加载到其中,然后从页面ѭ11中的<iframe>
中的页面中提取了<body>
。
我需要对iframe使用同源策略(本文展示了方法):
var iframe = document.createElement(\'iframe\');
iframe.style.display = \"none\";
jQuery(\'body\').append(iframe);
iframe.contentWindow.contents = data;
iframe.onload = function () {
var bodyHTML = jQuery(iframe).contents()
.find(\'body\').html();
// Use the bodyHTML as you see fit
jQuery(\'#error\').html(bodyHTML);
}
iframe.src = \'javascript:window[\"contents\"]\';
完成后,只需将ѭ8取出即可...
, 确保将事件绑定到按类过滤的文档($(document).on(\'click\',\'.my-class-name\',doThings);
)如果替换正文的html,则使用新的html重绘DOM时,直接完成的任何事件绑定($(\'.my-class-name\').on(\'click\',doThings);
)将被销毁。重新绑定将起作用,但是它还会留下旧事件和垃圾收集器必须清理的节点的指针-用更简单的术语来说,它可能会使页面变得越来越重,打开页面的时间越长。
我尚未在多个平台上对此进行测试,请谨慎使用。
// create a new html document
function createDocument(html) {
var doc = document.implementation.createHTMLDocument(\'\')
doc.documentElement.innerHTML = html
return doc;
}
$(\"a\").click(function (event) {
event.preventDefault();
$.get($(this).attr(\"href\"),function(data) {
$(\"body\").html($(createDocument(data)).find(\'body\').html);
});
});