首页 > 解决方案 > 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 页面在页面加载时打印出来,而不是在动态达到某个点后打印出来?

这样的事情甚至可以实现吗?

标签: javascriptphpjqueryinclude

解决方案


你不能在客户端运行 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;
  }
});

推荐阅读