我有一个带有以下 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函数。
有人能指出我正确的方向吗?谢谢!
最佳答案
这是不可能的,因为您将客户端行为与服务器端行为混合在一起。您需要做的是向服务器创建一个 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 个随机图像。这对于较小的数据集甚至一些更大的数据集可能会更好。
关于php - 如何在javascript中动态调用php函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/557778/