首页 > 解决方案 > 来自 jQuery $.ajax 调用的响应变量上的 javascript querySelector

问题描述

我正在使用 Bootstrap 开发一个系统,但在打印某些表格时遇到了问题。背景颜色未显示在屏幕上。

我终于找到了解决html2canvas问题的方法。

我可以简单地在我的 html 上查询选择一个元素,html2canvas 会在画布上“绘制”它,并且它会完全按照屏幕上显示的方式打印。

为此,请使用以下代码:

html2canvas(document.querySelector("#capture")).then(canvas => {
    document.body.appendChild(canvas)
});

我的问题是:我可以将 querySelector 与从 jQuery $.ajax 调用中获得的响应变量一起使用吗?

我尝试以多种方式做到这一点,但从未成功。这是一个例子:

$.ajax({
url: 'url',
type: 'POST',
success: function (data) {
	html2canvas($(data).querySelector("#selector")).then(canvas => {
		let wnd = window.open("about:blank", "");
		wnd.document.body.appendChild(canvas);
	});
}
});

安迪关于我如何做到这一点的想法?

标签: javascriptjqueryhtmlajaxhtml2canvas

解决方案


data可能是一个String包含 HTML。如果您想在 DOM 中使用它,您需要先将其解析为 DOMNodes。DOMParser您可以通过使用或 jQuery将字符串作为另一个元素的 innerHTML 插入来做到这一点$.parseHTML。我在下面的代码中使用了第一个。

$.ajax({
url: 'url',
type: 'POST',
success: function (data) {
  var template = document.createElement('template');//you could elements other than <template>
  template.innerHTML = data;//parses the html string into DOM Nodes
	html2canvas(template.content.querySelector("#selector")).then(canvas => {
		let wnd = window.open("about:blank", "");
		wnd.document.body.appendChild(canvas);
	});
}
});

警告,我不知道 html2canvas 并且它可能需要将元素插入到页面中......但我不这么认为。

编辑

作为检索已解析的 DOM 元素的示例:

var htmlString = "<div id='new_div'><p id='new_p'>New Element</p></div>";

var template = document.createElement('template');
template.innerHTML = htmlString;
//DOMNodes are parsed, but not attached to the document
console.log('new DOMNodes are "floating" in memory, dont exist in document');
console.log(document.querySelector('#new_div'));
console.log('should find the element in the template, which is not attached to the document');
console.log(template.content.querySelector('#new_div'));

document.body.appendChild(template.content);
console.log('attached nodes to the body. they should be findable on document now');
console.log(document.querySelector('#new_div'));

//via jquery
var newStuff = $.parseHTML(htmlString);//returns an array-like?
var actualNewDiv = newStuff[0];
console.log('jquery parsed reference to the DOMNodes');
console.log(actualNewDiv);//could be passed to html2canvas without querySelector-ing
console.log('since the root element IS the div, we cant query for it');
console.log(actualNewDiv.querySelector('#new_div'));
console.log('we CAN querySelect the p, because it is a child');
console.log(actualNewDiv.querySelector('#new_p'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


推荐阅读