此AJAX请求不会像beforeSend
处理程序那样返回任何64-Value-String。但是它作为alert
功能!我不知道如何做这个异步。问题是什么?
$imageMaps[0] = '1.jpeg';
$imageMaps[1] = '2.jpeg';
for (var k in $imageMaps) {
$file = $imageMaps[k];
$.ajax({
type: "POST",
async: 0,
beforeSend: function (xhr, settings) {
$base64 = convertImgToBase64($file);
alert($base64)
settings.data.img = $base64;
settings.data.url = $file;
},
url: '/request.php?imagePost=1',
data: {
img: '',
url: $file
},
success: function () {}
});
}
function convertImgToBase64(url) {
var img = new Image();
img.src = url;
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
dataurl = canvas.toDataURL("image/png");
alert(dataurl)
return dataurl;
}
}
答案 0 :(得分:0)
你实际上并没有从那个函数返回任何东西。试着这样做:
function convertImgToBase64(url) {
var img = new Image();
img.src = url;
return img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
dataurl = canvas.toDataURL("image/png");
alert(dataurl)
return dataurl;
}
}
我可能错了,所以如果不起作用,请对其进行评论。
答案 1 :(得分:0)
以下是解决方案:
$imageMaps[0] = '1.jpeg';
$imageMaps[1] = '2.jpeg';
for (var k in $imageMaps) {
$file=$imageMaps[k];
convertImgToBase64($url, function($base64Img,$url2){
$.ajax({
type: "POST",
async : 1,
url: '/request.php?imagePost=1',
data: {img:$base64Img,url:$url2},
xhr: function() {},
success: function(){}
});
})
}
function convertImgToBase64(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this,0,0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback(dataURL,url);
canvas = null;
};
img.src = url;
}