【发布时间】:2014-12-07 02:15:42
【问题描述】:
我觉得我没有完全理解 ajax 调用是如何工作的(我保证我试图理解,但虽然我认为我理解了,但我的代码并没有按预期工作)。 这就是我想要做的: 我有服务器端代码,它只返回一组图像 url。 对于每个图像,我正在使用客户端人脸检测库进行人脸检测。 在对所有图像进行人脸检测后,我需要在画布上一张一张地绘制它们(这不再真正相关了)。 实际发生的情况是,我首先收到“完成寻找面孔”的警报,然后才收到带有图像 URL 的警报,并且它对所有图像使用相同的 URL。 我还将“异步”设置为 false,因为我认为这会使事件的顺序按我的预期工作。 如果我不清楚,请告诉我,并提前非常感谢您!
//Call FB api from server side script
function callApi(userId, token) {
$.ajax({
"type": "GET",
"url": API_ROUTE + "?userid=" + userId + "&token=" + token,
"async": false, //setting to false because we don't want to start drawing before face detection is done
success: function(data, status, xhr) {
face_coords = []; //Array that stores face locations for each image (indexs are respective to
//image indexes in aImages)
for (var i = 0; i < data.length; i++) {
var img_url = data[i];
img_url.replace('https://', 'http://'); //To avoid cross-domain issues
// collect all images
var oImg = new Image();
oImg.crossOrigin = 'Anonymous';
oImg.src = img_url;
aImages.push(oImg);
$("#myPicture").attr("src", oImg.src).load(function() {
var coords = $('#myPicture').faceDetection();
//find the face detected with the highest confidence
if (coords.length > 0) {
var highest_confidence = 0,
highest_c = 0;
for (var c = 0; c < coords.length; c++) {
if (coords[c].confidence > highest_confidence) {
highest_confidence = coords[c].confidence;
highest_c = c;
}
}
}
face_coords.push(coords[highest_c]);
alert ("done with " + $('#myPicture').get(0).src)
});
}
}
});
alert("done with looking for faces");
var canvas = $('#myCanvas').get(0);
context = canvas.getContext('2d');
//draw first image
context.drawImage(aImages[0], 0, 0, CANVAS_WIDTH, aImages[0].height / aImages[0].width * CANVAS_WIDTH);
changeSlide(); //call on the first image in order to not waste 5 seconds
timer = setInterval(changeSlide, 5000); // set inner timer
}
【问题讨论】:
-
如果ajax调用成功就会调用success。什么让你困惑?
标签: javascript jquery ajax face-detection