javascript - PHP可以使用JS中设置的条件动态加载文件吗?
问题描述
当用户滚动到页面的某个部分时,我有一个想要在页面上插入的 PHP 包含。那可能吗?
就像是:
var hasPassedPoint = false;
$(window).scroll(function() {
var $this = $(this);
if ($this.scrollTop() > 400 && !hasPassedPoint) {
<?php
include $_SERVER['DOCUMENT_ROOT'].'/myFile.php';
?>
hasPassedPoint = true;
}
});
我试过了,但它并没有奏效,可能是因为完整的 php 页面在页面加载时打印出来,而不是在动态达到某个点后打印出来?
这样的事情甚至可以实现吗?
解决方案
你不能在客户端运行 php,页面渲染后唯一在客户端运行的是 Javascript,
要使用 Javascript + PHP 实现动态,您最常使用 XHR 或 Ajax / axios ...等,假设您想在特定元素上的事件之后显示来自 myFile.php 的数据
var hasPassedPoint = false;
$(window).scroll(function() {
var $this = $(this);
if ($this.scrollTop() > 400 && !hasPassedPoint) {
axios.get('/myFile.php').then(function (response) {
// this is the data from myFile in response
// you display it with
document.getElementById('urdiv').innerHtml = response.data
})
hasPassedPoint = true;
}
});
推荐阅读
- javascript - 在 JSON 中附加元素并且不要覆盖
- java - 如何使用 Jenkins 的 groovy 自动安装 Maven 和 Java JDK8?
- multithreading - 使用由`fork`创建的多个C线程的回调函数时,Rust Mutex不起作用
- sql - 递归地从同一个表的父子表中获取最后一条记录
- c++ - 如何获取 ERRORLOG.txt 中最深的调用堆栈条目?
- python - 方程组的解返回空集
- c++ - 从较大的数字类型转换为较小的数字类型时有哪些潜在的陷阱?
- javascript - 如何取消选择嵌套的 JSON 对象?
- laravel - Laravel - 预订系统的数据库设计
- groovy - 未定义变量时获取空响应数据