简体   繁体   English

XHR上的Javascript请求

[英]Javascript request over XHR

I am attempting to download a web page through XHR, and then render it in the browser (using document.write()), but when I do this, although the page is displayed, the jQuery's ready() function does not execute. 我试图通过XHR下载网页,然后在浏览器中呈现它(使用document.write()),但是当我这样做时,尽管页面已显示,但jQuery的ready()函数没有执行。 If I download the exact same page directly, it does execute. 如果我直接下载完全相同的页面,它将执行。 Is there something that needs to be done to make the page delivered through XHR execute the ready() function? 要使通过XHR传递的页面执行ready()函数,需要做些什么吗?

Don't use document.write() to replace page contents, it'll end in tears. 不要使用document.write()来替换页面内容,它会以眼泪结束。

Just find a suitable top-level element and use .replaceWith() to get rid of its existing contents and include the new contents retrieved from the XHR, eg: 只需找到合适的顶级元素,然后使用.replaceWith()摆脱其现有内容,并包含从XHR中检索到的新内容,例如:

$.get(url, function(html) {
    $(body).replaceWith($(html).find('body'));
});

Note that this won't replace the <head> , nor will it execute any additional Javascript blocks that might be included in the new content. 请注意,这不会替换<head> ,也不会执行任何可能包含在新内容中的其他Javascript块。

You can also use .load() 您也可以使用.load()

$(body).load(url);

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

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