jquery加载不读取字符串作为变量(php hybrid)

时间:2011-01-29 06:10:51

标签: php javascript jquery

我正在写一个javascript被jquery解析的字符串 - 它可以正常作为警报而不是jquery加载函数

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

尝试各种方式的字符串组合。击败。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

你需要在你的代码中添加php标签

<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>";

答案 1 :(得分:0)

使用闭包会为您提供更清晰的代码。

另外,使用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>";

答案 2 :(得分: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替换了动态部分