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

标签 php javascript 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?
}

但是,当页面加载时,会调用 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/

相关文章:

php - 如何将特定用户的通知标记为已读并在 laravel 5 中发布?

javascript - ajax 响应并在 Codeigniter 中提供良好链接后,如何在 Froala 编辑器中显示图像?

r - 如何在 df 中添加具有特定条件的列

javascript - 从一个表单字段获取条目并在数据库中搜索其相应数据并自动填充表单中的其他字段

php - 如何在 nextGen (galleryview template) wordpress 插件中增加图像的宽度?

使用 OOP 和 switch case 在 pdo 中更新 PHP

javascript - 在 Javascript 中,循环 3 个字符串的数组的可靠方法是什么?

javascript - slidetoggle 空 div 不应该工作

vb.net - VB.net逻辑可捕获函数错误

c++ - 抽象函数