我有一个带有以下js函数的index.php:
function returnImageString() {
return "<?php include 'inc/image.functions.php'; echo getRandomImages(7); ?>"; //This isn't dynamic; this will always return the same images. How do I fix this?
}但是,当页面加载时,将调用php脚本,并将结果添加到源代码中,如下所示:
function returnImageString() {
return "images/20.11.A1B9.jpg|images/8.14.47683.jpg|images/19.10.FBB9.jpg|images/21.12.9A.jpg|images/8.11.1474937909.jpg|images/8.15.99404.jpg|images/8.10.jpg|"; //This isn't dynamic; this will always return the same images. How do I fix this?
}我想要发生的是,每当我调用js函数(returnImageString)时,我希望它每次都调用php函数(因为php函数返回一个随机图像位置的字符串),而不是将字符串硬编码到js函数中。
谁能给我指个方向?谢谢!
发布于 2009-02-17 17:21:45
这是不可能的,因为您将客户端行为与服务器端行为混合在一起。您需要做的是创建一个到服务器的AJAX请求。
如果您正在使用像jQuery这样的库(这是您真正想要的,因为它让AJAX变得轻而易举),那么您应该这样做:
PHP代码(也许是randomImages.php?)
// query for all images
// $_GET['limit'] will have the limit of images
// since we passed it from the Javascript
// put them all in an array like this:
$images = array('images/20.11.A1B9.jpg','images/20.11.A1B9.jpg',...);
print json_encode($images); // return them to the client in JSON format.
exit;客户端Javascript
function getRandomImages(limit) {
// make request to the server
$.getJSON('/path/to/randomImages.php', {limit: limit}, function(data) {
// data is now an array with all the images
$.each(data, function(i) {
// do something with each image
// data[i] will have the image path
});
});
}或者,如果图像的数量是有限的,您可以跳过所有这些疯狂操作,简单地使用一个包含所有图像的数组,并从Javascript本身生成8个随机图像。这可能更适合较小的数据集,甚至更大的数据集。
发布于 2009-02-17 17:14:56
您不能直接这样做,因为PHP是在服务器上解释的,而您在客户端使用的是JavaScript。但是,如果您在服务器上创建了一个页面random-image.php,那么您可以使用AJAX获取数据,并在数据返回时在服务器端对其进行操作。
发布于 2009-02-17 17:17:06
您有两个选择:
在我看来,第二种选择似乎是最好的。
https://stackoverflow.com/questions/557778
复制相似问题