2011-01-29 70 views
0

我写了一个JavaScript字符串由jQuery的解析 - 它工作得很好作为警告,但不是在jQuery的负载功能jQuery的负载不读字符串作为变量(PHP混合动力)

PHP:

$imgData = 'http://www.domain.com/_image.php/_MG_4156.jpg' ; 

这是一个PHP脚本在运行中生成

<script type='text/javascript' language='javascript' charset='utf-8'> 
<!-- 
    var chart1img_".$i_gall." = new Image(); 
    var imgData = '".$imgData."'; 

    $(chart1img_".$i_gall.").load(function() { 
     $(this).hide(); 
     $('#thumb_img_div_".$i_gall."').removeClass('loading').append(this); 
     $(this).fadeIn(); 
    }).error(function() { 
     // notify the user that the image could not be loaded 
     alert(imgData); 
    }).attr('src', imgData); 
    //}).attr('src', 'http://www.domain.com/_image.php/_MG_4156.jpg'); 

//--> 
</script>"; 

缩略图如果我硬派它工作的字符串。 如果我使用它作为imgData变量,它会失败,但警报使用imgData

尝试过的字符串组合可以用各种方法。击败。有任何想法吗?

回答

0

不知道是什么问题,除了它是在充分的人物之一可变吗?:

var imgData = 'http://www.domain.com/_image.php/".$r_gall['image']."?width=145&height=205&cropratio=145:205&image=/images_cms/".$r_gall['image']."'; 

但我在JS中保留了很多字符串,只是将动态用PHP编写的集成电路零件

2

你需要在你的代码

<script type='text/javascript' language='javascript' charset='utf-8'> 
<!-- 
    var chart1img_"<?php echo $i_gall;?>" = new Image(); 
    var imgData = '<?php echo $imgData?>'; 

    $("chart1img_<?php echo $i_gall;?>").load(function() { 
     $(this).hide(); 
     $('#thumb_img_div_<?php echo $i_gall;?>').removeClass('loading').append(this); 
     $(this).fadeIn(); 
    }).error(function() { 
     // notify the user that the image could not be loaded 
     alert(imgData); 
    }).attr('src', imgData); 
    //}).attr('src', 'http://clients.flatearth.co.uk/benhopper/project/_image.php/_MG_4156.jpg'); 

//--> 
</script>"; 
+0

Javascript正在被PHO写出所以不需要回显 – JulianB 2011-01-29 07:00:55

0

添加php标记使用闭包会给你一个更干净的代码。请使用json_encode向JavaScript发送值。

例如,

echo " 
<script type='text/javascript'> 
(function() { 

    var image = new Image(), 
     imgData = " . json_encode($imgData) . ", 
     i_gall = " . json_encode($i_gall) . "; 

    $(image).load(function() { 
     $(this).hide(); 
     $('#thumb_img_div_' + i_gall).removeClass('loading').append(this); 
     $(this).fadeIn(); 
    }).error(function() { 
     // notify the user that the image could not be loaded 
     alert(imgData); 
    }).attr('src', imgData); 

})(); 
</script>"; 

这最小化嵌入PHP值来定义它们如JavaScript变量数。

你也可以把它们的功能:

<script type='text/javascript'> 
function loadAndShowImage(imgData, i_gall) { 

    var image = new Image() 

    $(image).load(function() { 
     $(this).hide(); 
     $('#thumb_img_div_' + i_gall).removeClass('loading').append(this); 
     $(this).fadeIn(); 
    }).error(function() { 
     // notify the user that the image could not be loaded 
     alert(imgData); 
    }).attr('src', imgData); 

} 
</script> 

,然后只输出动态部分:

echo " 
<script type='text/javascript'> 
    loadAndShowImage(" . json_encode($imgData) . ", " . json_encode($i_gall) . "); 
</script>"; 
+0

唉json_encode并没有这样做 – JulianB 2011-01-29 06:59:27