weixin_33694620 2017-01-08 01:50 采纳率: 0%
浏览 17

跨两页的PHP变量

Sorry if the title is inaccurate, but I need help syncing a variable across two pages, when the second is loading with ajax (Instant Messanging)

I need it to fetch a page with ajax, just if I define a variable earlier on in the same document it doesn't apply to the ajax page (I can't use include)

page1.php

<?php $variable = 'apples'; ?>
<script src="script.js"></script> <!--Contains ajax for page2.php-->

<div id="gets_parsed_here"></div>

And it uses ajax to get page2.php

page2.php

<?php echo $variable; ?>

This isn't my actual code, but it's similar to what it should do.

Any help would be appreciated a lot.

  • 写回答

2条回答 默认 最新

  • 程序go 2017-01-08 08:00
    关注

    I think what you are asking is how to pass a variable from page1.php to page2.php, when page1.php calls page2.php via AJAX.

    As your script is in an external JS file, there are 2 steps involved:

    • Get the variable in Javascript, so script.js can access it. How you do this depends on what you're actually doing, but here's a simple example. Add the following somewhere on page1.php before you include script.js:

      <script>
          var fruit = <?php echo json_encode($variable); ?>;
      </script>
      

      Alternatively it might make more sense to read the variable from wherever it already appears on the page, eg (with jQuery):

      var fruit = $('#someID).val();
      
    • Pass the Javascript variable on to page2.php in the AJAX request. You can do that by passing it as a GET or POST parameter. You haven't shown how you're doing the AJAX call in script.js, but here's how you can do it in jQuery (this is GET):

      $.ajax({
          url: 'http://your-site/page2.php',
          data: { 'fruit': fruit },
          success: function(resp) {
              // AJAX is done, use the response
          }
      });
      

      This issues a request to http://your-site/page2.php?fruit=apples. And as you know from PHP 101 you can access the value of fruit in page2.php like:

      echo $_GET['fruit'];
      

      If you are using a framework use it's preferred method of accessing the input request parameters instead of accessing $_GET directly.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c