【问题标题】:Pass li data-value via AJAX onclick back to same page通过 AJAX onclick 将 li 数据值传递回同一页面
【发布时间】:2015-02-28 10:02:07
【问题描述】:

我正在尝试将我单击的

  • 的数据值传递给同一页面中的 PHP。我正在使用 AJAX 将数据传递给 PHP,以用于查询。我认为 ajax 请求正在运行,但 if 中的 php 代码没有运行。

    代码:

    offices.php

    <?php
        include 'connect.php';
        $page = 'offices';
        include 'header.php';
    
        if (isset($_POST['postdata'])){
            $filter1 = $_POST['postdata'];
            echo $filter1;
        }
    ?>
    
    <!DOCTYPE html>
     <html>
        <head>
           <script src="js/jquery.min.js"></script>
        </head>
        <body>
    
            <div class="filter1">
                <ul>
                    <li class="fteacher" data-value="teacher">Professor</li>
                    <li class="foffice" data-value="office">Gabinete</li>
                </ul>
            </div>
    
            <script src="js/offices.js"></script>
        </body>
     </html>
    

    offices.js

    $('.filter1 li').click(function(){
     $.ajax({ 
         type: 'POST',
         url: 'offices.php',
         data: {'postdata': $(this).attr('data-value')},
         success: function(msg){
               alert('Success'); 
          }
     });
    });
    
  • 【问题讨论】:

    • 为什么你认为 PHP 没有被执行?

    标签: php jquery html ajax post


    【解决方案1】:

    我尝试了您提供的代码,但不得不在您的 PHP 脚本开头省略这两个包含,并且它有效。测试是在 if 子句中使用 file_put_contents("test.txt", "test"); 完成的。

    您可以使用alert(msg) 查看 PHP 脚本返回的内容。请注意,PHP 部分之后的所有内容也会返回。在 PHP 中使用 error_reporting(E_ALL) 来搜索包含的脚本中的问题也可能会有所帮助。

    【讨论】:

      【解决方案2】:

      请试试这个。希望您只期待输出$filter1

      <?php
         if (isset($_POST['postdata'])){
            $filter1 = $_POST['postdata'];
            echo $filter1;
         }else {
            include 'connect.php';
            $page = 'offices';
            include 'header.php';
      ?>
          <!DOCTYPE html>
           <html>
              <head>
                 <script src="js/jquery.min.js"></script>
              </head>
              <body>
                  <div class="filter1">
                      <ul>
                          <li class="fteacher" data-value="teacher">Professor</li>
                          <li class="foffice" data-value="office">Gabinete</li>
                      </ul>
                  </div>
                  <script src="js/offices.js"></script>
              </body>
           </html>
          <?php
              }
          ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-22
        • 2015-12-20
        • 1970-01-01
        • 2018-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多