编辑:我知道我的问题是,我不能检查图像是否好,直到它有时间加载。我试图检查宽度,并在它或src更改之后返回(使用onerror设置src)。虽然我总是遇到竞争条件,并且在高度和宽度或src更改之前出错。当我重新加载时,图像被缓存并且工作正常。我不知道如何避免这种情况。这里是我当前的代码(也不工作,它会循环,直到firefox抱怨。)我设置这个函数返回到一个变量。有一些写在我用来看它有多远,它停在while循环。我尝试过使用getTimeout('tstit = chkload(“thisisatest”,tinypth);',250);但那也没用。我希望我能迫使这个以加载...图像或错误,如果它不存在的返回地址
function buildimg(tehname,myc,pth1,pth2,tinypth)
{
var myimg = pth1+tehname+"/"+tehname+"-"+myc+".jpg";
buildtest("thisisatest",myimg,tinypth);
var testimg = document.getElementById("thisisatest");
var tstit = chkload("thisisatest",tinypth);
while(tstit == false) {
document.write(tstit);
tstit = chkload("thisisatest",tinypth);
}
alert(testimg.src+'-'+testimg.width+'-'+testimg.height);
if((testimage.width > 20) && (testimage.height > 20)) {
return myimg;
}
else if(typeof pth2 == "undefined") {
myimg = "error";
return myimg;
}
else {
myimg = buildimg(tehname,myc,pth2);
return myimg;
}
document.write('No return error in buildimg.');
return "error";
}
/*Builds a hidden img tag for testing images*/
function buildtest(itsid,itssrc,tinypath) {
if(document.getElementById(itsid)) {
var imgobj = document.getElementById(itsid);
imgobj.remove();
}
document.write('<img id="'+itsid+'" style="display: none;" src="'+itssrc+'" onerror="swaponerr(\''+itsid+'\',\''+tinypath+'\')" />');
}
/*Swaps the image to a small picture, so we can detect if it worked*/
function swaponerr(tagid, tinypath) {
var theimg = document.getElementById(tagid);
theimg.onerror = '';
theimg.src = tinypath;
}
/*Recurses to return when the image is loaded*/
function chkload(loadid,tinychk) {
var tehobj = document.getElementById(loadid);
document.write(tehobj.width+'x'+tehobj.height+'x'+tehobj.src);
if((tehobj.naturalWidth > 20) && (tehobj.naturalHeight > 20)) {
return true;
}
if(tehobj.src == tinychk) {
return true;
}
return false;
}
我需要测试的图像,如果不存在返回错误。下面的代码工作正常,我的服务器上:
不幸的是,我试图做这搞砸系统我的工作使用上。我们有jquery,但系统将用户文件存储在独立服务器上的代码中,所以ajax将无法工作。我希望这将最终以.js文件形式存在。
现在我已经得到了代码开头:
function buildimg(tehname,myc,pth1,pth2)
{
var myimg = pth1+tehname+"/"+tehname+"-"+myc+".jpg";
var tehimage = new Image();
tehimg.src = myimg;
我试图具有的功能加载图像,并检查其宽度,但我总是得到0,因为我不能预先加载图片不知道它们有多少(我不希望有大量错误的请求数量过高)。出于某种原因(至少在ff4上,因为这是我的首要目标)tehimage。完成总是返回false。我已经尝试使用onerror和onload由一个全局变量,和一些其他方法。我必须承认,虽然我不是很熟悉JavaScript,所以我的回调可能不起作用。
请帮忙,我越来越绝望!
谢谢,Truk
为什么ajax无法正常工作?我不明白 – ariel 2011-05-11 06:40:18
由于安全问题,Ajax不会执行跨服务器请求。它可以在我自己的网站上正常运行,所有内容都位于一台服务器上。 – Truk 2011-05-11 12:30:11