3

I'am developing a zoom tool in my shopping cart and I am stuck on how to call a PHP variable in a jQuery function.

Here's my code :

jQuery(document).ready(function($){
$('#image1').addimagezoom({ // single image zoom
    zoomrange: [3, 10],
    magnifiersize: [800,300], 
    magnifierpos: 'right',
    cursorshade: true,
    largeimage: "php variable" //we add the directory of the image.
});
});

I need to put

$src ="images/products/".mysql_result($execute_select_product_query,0,'image1')."

in my function where I put PHP variable.

4

5 回答 5

16

您有两个或三个选项:如果 Javascript 在 php 文件中,您可以

var phpVar = <?php echo $var; ?>;

否则,如果 Javascript 在任何地方,您可以执行以下操作:

<input type="hidden" id="phpVar" value="<?php echo $var; ?>">

然后访问它

$('#phpVar').val();

示例 1:

jQuery(document).ready(function($){
$('#image1').addimagezoom({ // single image zoom
    zoomrange: [3, 10],
    magnifiersize: [800,300], 
    magnifierpos: 'right',
    cursorshade: true,
    largeimage: <?php echo $var; ?> //we add the directory of the image.
});
});

示例 2:
HTML:

<input type="hidden" id="phpVar" value="<?php echo $var; ?>">

Javascript

jQuery(document).ready(function($){
$('#image1').addimagezoom({ // single image zoom
    zoomrange: [3, 10],
    magnifiersize: [800,300], 
    magnifierpos: 'right',
    cursorshade: true,
    largeimage: $('#phpVar').val(); //we add the directory of the image.
});
});
于 2013-08-14T11:23:38.713 回答
5

像这样做:

largeimage: "<?php echo $src; ?>"
于 2013-08-14T11:19:56.060 回答
4

PHP是服务器端语言,javascript是用户端语言。不要混合它。只需使用ajax。或者,如果您已将脚本包含在 PHP 文件中,则可以将其写入代码:

  <?php $srcImg = 'Some value'; ?>
  jQuery(document).ready(function($){
    $('#image1').addimagezoom({ // single image zoom
        zoomrange: [3, 10],
        magnifiersize: [800,300], 
        magnifierpos: 'right',
        cursorshade: true,
        largeimage: "<?php echo $srcImg; ?>" //we add the directory of the image.
    });
  });

我们使用数据属性

<body data-phpvar="<?php echo $srcImg; ?>">

在js中:

var phpvar = $("body").attr("data-phpvar");
于 2013-08-14T11:23:59.267 回答
2

您可以使用 php 标签来回显您的变量:

jQuery(document).ready(function($){
$('#image1').addimagezoom({ // single image zoom
    zoomrange: [3, 10],
    magnifiersize: [800,300], 
    magnifierpos: 'right',
    cursorshade: true,
    largeimage: "<?=$your_php_variable?>" //we add the directory of the image.
});
});

编辑:如果 jQuery 不包含在 php 文件中,那么您可以在 php 文件中声明一个 javascript 变量:

<?
php code
?>
<script type="text/javascript">
var my_js_variable = '<?=$my_php_variable?>';
</script>
<?
php code
?>
于 2013-08-14T11:22:53.137 回答
1

将 php 标签添加到您的 jquery 中"<?php echo $sample; ?>"

jQuery(document).ready(function($){
$('#image1').addimagezoom({ // single image zoom
    zoomrange: [3, 10],
    magnifiersize: [800,300], 
    magnifierpos: 'right',
    cursorshade: true,
    largeimage: "<?php echo $sample;?>" //we add the directory of the image.
});
});
于 2013-08-14T11:24:17.640 回答