我有一個頁面上的svgs被轉換爲canvas,然後成功發佈html2canvas數據。我遇到的麻煩是在發佈html2canvas數據後提交表單。我試圖簡單地使用如何在ajax中延遲提交表單然後
$('#chartInfo').submit()
在AJAX成功和錯誤,但不執行。所以,我試圖玩延遲下面提交表單,但我得到ajaxDfd是未定義的?我不確定我在哪裏出錯。我猜這是因爲我在ajax中使用延遲?
$(document).ready(function() {
$('#save_dashboard').click(function() {
// Declare an array to store all deferred objects from each svg element
var svgDfds = [],
ajaxDfd
targetElem = $('#contentzone-outer');
targetElem.find('svg').each(function() {
var dfd = new $.Deferred(),
svg = $(this),
canvas = $('<canvas></canvas>');
svg.replaceWith(canvas);
// Get the raw SVG string and curate it
var content = svg.wrap('<p></p>').parent().html();
content = content.replace(/xlink:title='hide\/show'/g, '');
content = encodeURIComponent(content);
svg.unwrap();
// Create an image from the svg
var image = new Image();
image.src = 'data:image/svg+xml,' + content;
image.onload = function() {
canvas[0].width = image.width;
canvas[0].height = image.height;
// Render the image to the canvas
var context = canvas[0].getContext('2d');
// Resolve or reject the deferred
dfd.resolve(context.drawImage(image, 0, 0));
};
// Push deferred object into array
svgDfds.push(dfd);
}); // end of targetElem.find('svg').map(function() {...});
// Check for all deferreds
$.when.apply($, svgDfds).then(function(_canvas) {
console.log('svgDfds resolve done', _canvas);
ajaxDfd = new $.Deferred();
$('#contentzone-outer').html2canvas({
onrendered: function (canvas) {
//Set dashboardPng value to image data (base-64 string)
var dashboardPng = canvas.toDataURL('image/png');
console.log('dashboardPng: ' + dashboardPng);
$.ajax({
url:'save_dashboard_image.php',
data:{dashboardPngData: dashboardPng},
type:'POST',
dataType:'json',
success: function(){
console.log('success');
}
,
error: function(xhr, status, error){
console.log('The requested page was: ' + document.URL +
'. The error number returned was: ' + xhr.status +
'. The error message was: ' + error);
}
})
.done(function(){
console.log('AJAX success()');
})
.always(function(){
ajaxDfd.resolve(console.log('AJAX complete()'));
return ajaxDfd.promise();
})
.fail(function(){
console.log('AJAX error()');
}); // end of save_dashboard_image.php
} // end of html2canvas
}); // end of onrendered
}); // end of $.when.apply($, svgDfds).then(function(_canvas) {...}
ajaxDfd.done(function(){
$('#chartInfo').submit();
});
}); // end of save_dashboard click function
}); // end of document ready
謝謝,我發現之後。但仍然沒有骰子。 – imparante
已更新answear – alexeiTruhin
謝謝alexeiTruhin建議done()inside then(),我將不得不在下一次嘗試,但我發現我需要通過AJAX發佈表單,然後才能在JavaScript中獲得這一點。再次感謝! – imparante