如何在javascript中动态调用php函数

bry*_*yan 4 javascript php function

我有一个带有以下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?
}
Run Code Online (Sandbox Code Playgroud)

但是,当页面加载时,调用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?
 }
Run Code Online (Sandbox Code Playgroud)

我想要发生的是每当我调用js函数(returnImageString)时,我希望它每次调用php函数(因为php函数返回一串随机图像位置),而不是在js函数中对字符串进行硬编码.

有人能指出我正确的方向吗?谢谢!

Pao*_*ino 19

这是不可能的,因为您将客户端行为与服务器端行为混​​合在一起.您需要做的是向服务器创建一个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;
Run Code Online (Sandbox Code Playgroud)

客户端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
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

或者,如果图像的数量是有限的,你可以跳过所有这些疯狂,只需要一个包含所有图像的数组,并从Javascript本身生成8个随机图像.对于较小的数据集甚至是较大的数据集,这可能会更好.