gpt4 book ai didi

php - 如何将 PHP 插入到 jQuery 中?

转载 作者:行者123 更新时间:2023-11-30 18:31:44 29 4
gpt4 key购买 nike

我知道不能从客户端 (JavaScript) 执行 PHP,但是什么是合适的方法呢?用 PHP 编写我的 jQuery?这是我正在寻找的示例。

<!-- Wordpress template URL -->
<div id="template_directory" style="display: none;">
<?php bloginfo('template_url'); ?>
</div>

<!-- Fetch with jQuery -->
var templDirec = $("#template_directory").html();
var imgHTML = '<img src="' + templDirec + '/images/my-image.jpg" />';

由于我是新手,所以最好提供简单的描述性答案。让 js 和 php 协同工作的最佳方式是什么?谢谢

最佳答案

首先,你应该用script-tag包裹js代码:

<!-- Wordpress template URL -->
<div id="template_directory" style="display: none;">
<?php bloginfo('template_url'); ?>
</div>

<!-- Fetch with jQuery -->
<script type="text/javascript">
var templDirec = $("#template_directory").html();
var imgHTML = '<img src="' + templDirec + '/images/my-image.jpg" />';
</script>

如果你想将一些数据从 PHP 传递到 JS,请使用 echo:

<script type="text/javascript">
var templDirec = $("#template_directory").html();
var imgHTML = '<img src="<?php echo $image ?>" />';
</script>

其中 $image-php 变量。通常,您可以使用 PHP 和 html 生成任何 JS 代码。

要将数据从 JS 传递到 PHP(从客户端到服务器),请使用 AJAX

希望对您有所帮助。

关于php - 如何将 PHP 插入到 jQuery 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9451212/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com