donglengyuan6826 2018-07-12 17:10
浏览 121
已采纳

带有参数的AJAX页面加载/ url导致空白页面

Good afternoon,

I am working on a website for a friend's gaming fansite. Utilizing a URI function and ajax URL loads, I'm setting it up so when they visit a page, the URL changes and that page's content loads, while leaving the top portion of the website static. The logo, radio box and navigation bar is the static portion.

Everything is working as intended so far, but when a page is used that's using a specific ID, it loads up a blank page. I'll show what I've done with the Badges page for an example.

Here's my HTACCESS:

Header set Access-Control-Allow-Origin *
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "*"
Options -MultiViews
RewriteEngine On
RewriteRule ^badges/([0-9]+)/?$ badges.php?id=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

Here's the URI script:

<?php
  function getCurrentUri() {
      $basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
      $uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
      if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
      $uri = '/' . trim($uri, '/');
      return $uri;
  }
  $base_url = getCurrentUri();
  $routes = array();
  $routes = explode('/', $base_url);
  foreach($routes as $route) {
      if(trim($route) != '')
          array_push($routes, $route);
  }
  if ($base_url == "/" || $base_url == "/home") {
      $page = "home";
  } elseif ($base_url == "/about") {
      $page = "about";
  } elseif ($base_url == "/badges") {
      $page = "badges";
  }
?>

Here's my AJAX call:

$(document).ready(function() {
        $.ajax({
            url: '<?php echo $page; ?>.php',
            success: function(content) {
                $("#contfill").html(content);
                history.pushState(null, '', '<?php echo $page; ?>');
                homePageInit();
            }
        });
});

When www.domain.com/badges is used, it loads the page correctly as shown here:

Badge page working correctly

The first badge's ID is 324. When www.domain.com/badges/324 is used, it loads the data correctly, but the page is blank as shown here:

Badge page not working correctly

Does anyone know why this would be?

EDIT

I added in a alert('$base_url'); to see what it would be. When using www.domain.com/badges, it shows as /badges. When using www.domain.com/badges/324 no alert pops up, so it seems that it's going directly to badges.php. Is that due to the HTACCESS?

SECOND EDIT

Here is my badges.php script:

<?php require('../panel/includes/config.php'); ?>
      <div class="row">
        <div class="col-md-12">
          <div class="panel panel-default">
            <div class="panel-heading bg-color-blue">
              <h3 class="panel-title"><i class="fa fa-newspaper-o" aria-hidden="true"></i> Badge Guides</h3>
            </div>
            <div class="panel-body">
              <p>
                  <img src="assets/images/1badge_guides.png" alt="Guides" class="img-responsive img-center">
                  <?php
                    if (isset($_GET["id"])) {
                        $id = $_GET["id"];
                        $newsQuery = $dbh->prepare("SELECT * FROM news WHERE id=:id");
                        $newsQuery->execute(array(":id"=>$id));
                        $newsQueryData = $newsQuery->fetch(PDO::FETCH_ASSOC);
                  ?>
                  <br>
                  <a href="https://twitter.com/share?url=http://habbfinity.ca/badge.php?id=<?php echo $id; ?>&text=New badge guide posted!" class="btn btn-info">Tweet</a>
                  <br>
                  <?php
                        echo htmlspecialchars_decode($newsQueryData['article']);
                    } else {
                        $reqInfo2 = $dbh->prepare("SELECT n.id,
                                                       n.image,
                                                       n.title,
                                                       n.category,
                                                       n.description,
                                                       n.article,
                                                       n.active,
                                                       n.level,
                                                       n.available,
                                                       n.author,
                                                       n.stamp,
                                                       c.cat_num,
                                                       c.cat_name,
                                                       a.active_num,
                                                       a.active_name,
                                                       av.avail_num,
                                                       av.avail_name,
                                                       l.level_num,
                                                       l.level_name
                                                FROM news n
                                                INNER JOIN news_cat c
                                                    ON n.category = c.cat_num
                                                INNER JOIN active_cat a
                                                    ON n.active = a.active_num
                                                INNER JOIN avail_cat av
                                                    ON n.available = av.avail_num
                                                INNER JOIN level_cat l
                                                    ON n.level = l.level_num
                                                WHERE n.category = 10 AND n.active = 1
                                                ORDER BY n.stamp DESC");
                        $reqInfo2->execute();
                  ?>
                  <p class="text-center">
                    <strong>BADGE GUIDES</strong>
                  </p>
                  <table class="table table-striped">
                    <thead>
                      <tr>
                        <th>Badge</th>
                        <th>Title</th>
                        <th>Description</th>
                        <th>Level</th>
                        <th>Availability</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php
                        while ($reqInfoData = $reqInfo2->fetch(PDO::FETCH_ASSOC)) {
                      ?>
                      <tr class="bg-success">
                        <td><?php echo "<img src=\"{$reqInfoData['image']}\" class=\"img-responsive\">"; ?></td>
                        <td><?php echo "<a href=\"#badge\" id=\"badge\" value=\"{$reqInfoData['id']}\">{$reqInfoData['title']}</a>"; ?></td>
                        <td><?php echo $reqInfoData['description']; ?></td>
                        <td><?php echo $reqInfoData['level_name']; ?></td>
                        <td>
                          <?php
                            if ($reqInfoData['avail_name'] == "Available") {
                                echo "<span style=\"color: green;\">{$reqInfoData['avail_name']}</span>";
                            } else {
                                echo "<span style=\"color: red;\">{$reqInfoData['avail_name']}</span>";
                            }
                          ?>
                        </td>
                      </tr>
                      <?php
                        }
                      ?>
                    </tbody>
                  </table>
                  <?php
                    }
                  ?>
                </p>
            </div>
          </div>
        </div>
      </div>

Here is the index.php page:

<?php
  function getCurrentUri() {
      $basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
      $uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
      if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
      $uri = '/' . trim($uri, '/');
      return $uri;
  }
  $base_url = getCurrentUri();
  $routes = array();
  $routes = explode('/', $base_url);
  foreach($routes as $route) {
      if(trim($route) != '')
          array_push($routes, $route);
  }
  if ($base_url == "/" || $base_url == "/home") {
      $page = "home";
  } elseif ($base_url == "/about") {
      $page = "about";
  } elseif ($base_url == "/badges") {
      $page = "badges";
  }
  require('../panel/includes/config.php');
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Habbfinity</title>
    <link rel="stylesheet" type="text/css" href="assets/css/normalize.css">
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/ie10-viewport-bug-workaround.css">
    <link rel="stylesheet" type="text/css" href="assets/css/custom.css">
  </head>
  <body>
    <div id="wrapper" class="container well">
      <header>
        <section id="brand" class="row">
          <div class="col-md-8">
            <img src="assets/images/habbfinitylogo.png" alt="Habbfinity" class="img-responsive img-center">
          </div>
          <div class="col-md-4">
            <div class="panel panel-default radpan">
              <div class="panel-body">
                <?php
                  date_default_timezone_set('Europe/London');
                  $timecheck = date("H:00");
                  $timecheckwhour = strtotime($timecheck) + 60*60;
                  $newtimecheck = date("H:00", $timecheckwhour);
                  $daycheck = date("N");
                  $djQuery = $dbh->prepare("SELECT * FROM timetable WHERE day=:day AND time=:time");
                  $djQuery->execute(array(":day"=>$daycheck, ":time"=>$timecheck));
                  $djQueryData = $djQuery->fetch(PDO::FETCH_ASSOC);
                  if (isset($djQueryData) || $djQueryData != "") {
                      $djQuery2 = $dbh->prepare("SELECT * FROM users WHERE djname=:dj");
                      $djQuery2->execute(array(":dj"=>$djQueryData['dj']));
                      $djQueryData2 = $djQuery2->fetch(PDO::FETCH_ASSOC);
                  }
                  $djQuery3 = $dbh->prepare("SELECT * FROM timetable WHERE day=:day AND time=:time");
                  $djQuery3->execute(array(":day"=>$daycheck, ":time"=>$newtimecheck));
                  $djQuery3Data = $djQuery3->fetch(PDO::FETCH_ASSOC);
                  if (isset($djQuery3Data) || $djQuery3Data != "") {
                      $djQuery4 = $dbh->prepare("SELECT * FROM users WHERE djname=:dj");
                      $djQuery4->execute(array(":dj"=>$djQuery3Data['dj']));
                      $djQueryData4 = $djQuery4->fetch(PDO::FETCH_ASSOC);
                  }
                  $djSays = $dbh->prepare("SELECT * FROM dj_says ORDER BY id DESC LIMIT 1");
                  $djSays->execute();
                  $djSaysData = $djSays->fetch(PDO::FETCH_ASSOC);
                ?>
                <audio autoplay id="player">
                  <source src="http://procyon.shoutca.st:8930/stream" type="audio/mp4">
                  <source src="http://procyon.shoutca.st:8930/stream" type="audio/ogg">
                </audio>
                <form method="post">
                  <p class="text-center">
                    <button type="button" class="btn btn-trans" onclick="document.getElementById('player').play()"><i class="fa fa-play galaxy" aria-hidden="true"></i></button>
                    <button type="button" class="btn btn-trans" onclick="document.getElementById('player').pause()"><i class="fa fa-pause galaxy" aria-hidden="true"></i></button>
                    <button type="button" class="btn btn-trans" onclick="javascript:ajaxpage('requests.php', 'contfill');"><i class="fa fa-comment galaxy" aria-hidden="true"></i></button>
                    <button type="submit" class="btn btn-trans" value="like" name="like"><i class="fa fa-heart galaxy" aria-hidden="true"></i></button>
                  </p>
                  <p>
                    <div class="row">
                      <div class="col-md-3">
                        <img src="https://www.habbo.com/habbo-imaging/avatarimage?hb=image&user=augmented_Runes&headonly=0&direction=4&head_direction=2&action=wav&gesture=&size=m" class="img-responsive img-center">
                      </div>
                      <div class="col-md-9">
                        <i class="fa fa-music" aria-hidden="true"></i> <span id="cc_strinfo_song_Habbfinity00" class="cc_streaminfo"></span>
                        <br>
                        <i class="fa fa-headphones" aria-hidden="true"></i> <span id="cc_strinfo_listeners_Habbfinity00" class="cc_streaminfo"></span> Listeners
                        <br>
                        <i class="fa fa-user" aria-hidden="true"></i> <span id="cc_strinfo_title_Habbfinity00" class="cc_streaminfo"></span>
                      </div>
                    </div>
                    <div class="row">
                      <div class="col-md-12">
                        <p class="marquee2">
                          <span><?php echo $djSaysData['message']; ?></span>
                        </p>
                      </div>
                    </div>
                    <div class="row">
                      <div class="col-md-12" style="margin-top: 20px;">
                        <input id="vol-control" class="myrange" type="range" min="0" max="100" step="1" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)"></input>
                      </div>
                    </div>
                  </p>
                </form>
                <?php
                  if (isset($_POST['like']) && isset($djQueryData2['habbo']) && $djQueryData2['habbo'] != "") {
                      $dj = $djQueryData2['habbo'];
                      $ip = $_SERVER['REMOTE_ADDR'];
                      $cur_time = time();
                      $djLikes = $dbh->prepare("SELECT * FROM djlikes WHERE dj=:dj AND likedip=:ip");
                      $djLikes->execute(array(":dj"=>$dj, ":ip"=>$ip));
                      $djLikesData = $djLikes->fetch(PDO::FETCH_ASSOC);
                      if ($djLikesData['likedip'] != "") {
                          $lasttime = $djLikesData['lastliked'];
                          $diff = abs($cur_time - $lasttime);
                          if ($diff > 3600) {
                              $AddLikes = $dbh->prepare("UPDATE djlikes SET likes = likes + 1 WHERE likedip=:ip");
                              $AddLikes->execute(array(":ip"=>$ip));
                              echo "Thank you for liking the DJ!";
                          } else {
                              echo "Please wait an hour before liking the DJ again!";
                          }
                      } else {
                          $AddLikes = $dbh->prepare("INSERT INTO djlikes VALUES (:habbo, :time:, :ip, 1)");
                          $AddLikes->execute(array(":habbo"=>$djQueryData2['habbo'], ":time"=>$cur_time, ":ip"=>$ip));
                          echo "Thank you for liking the DJ!";
                      }
                  }
                ?>
              </div>
              <div class="radimageoverdiv"><i class="fa fa-rocket galaxyl" aria-hidden="true"></i></div>
            </div>
          </div>
        </section>
        <nav class="navbar navbar-default">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
          </div>
          <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
              <li><a href="#home" id="home"><i class="fa fa-home" aria-hidden="true"></i> HOME</a></li>
              <li class="dropdown">
                <a href="" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="fa fa-info-circle" aria-hidden="true"></i> HABBFINITY <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#about" id="about">About Us</a></li>
                  <li><a href="#staff" id="staff">Our Team</a></li>
                  <li><a href="#contactus" id="contactus">Contact Us</a></li>
                  <li><a href="#sitenews" id="sitenews">Site News</a></li>
                  <li><a href="https://twitter.com/Habbfinity" target="_blank">Follow Our Twitter!</a></li>
                </ul>
              </li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="fa fa-newspaper-o" aria-hidden="true"></i> QUEST <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#badges" id="badges">Badge Guides</a></li>
                  <li><a href="#wired" id="wired">Wired Guides</a></li>
                  <li><a href="#news" id="news">News</a></li>
                </ul>
              </li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="fa fa-gamepad" aria-hidden="true"></i> EVENTS <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#events" id="events">Events Timetable</a></li>
                  <li><a href="#howto" id="howto">How To Play</a></li>
                </ul>
              </li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="fa fa-headphones" aria-hidden="true"></i> RADIO <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#radio" id="radio">Radio Timetable</a></li>
                  <li><a href="#requests" id="requests">Request Line</a></li>
                </ul>
              </li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="fa fa-star" aria-hidden="true"></i> GOODIES <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="" data-toggle="modal" data-target="#HabboImager">Habbo Imager</a></li>
                </ul>
              </li>
              <li><a href="https://www.habbfinity.ca/forum/" target="_blank"><i class="fa fa-comments" aria-hidden="true"></i> FORUM</a></li>
            </ul>
          </div>
        </nav>
      </header>
      <div id="contfill">
      </div>
      <a id="back-to-top" href="#" class="btn btn-primary btn-lg back-to-top" role="button" title="Click to return on the top page" data-toggle="tooltip" data-placement="left"><span class="glyphicon glyphicon-chevron-up"></span></a>
    </div>
    <div class="modal fade" tabindex="-1" role="dialog" id="HabboImager">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Habbo Imager</h4>
          </div>
          <div class="modal-body">
            <?php include 'imager.php'; ?>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>
    <script src="assets/js/jquery-3.3.1.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/js/respond.min.js"></script>
    <script src="assets/js/ie10-viewport-bug-workaround.js"></script>
    <script src="imagerscript.js"></script>
    <script language="javascript" type="text/javascript" src="https://procyon.shoutca.st/system/streaminfo.js"></script>
    <script>
      window.SetVolume = function(val) {
          var player = document.getElementById('player');
          player.volume = val / 100;
      }
      function homePageInit() {
          $('[data-toggle="tooltip"]').tooltip();
          $(window).scroll(function() {
              if ($(this).scrollTop() > 50) {
                  $('#back-to-top').fadeIn();
              } else {
                  $('#back-to-top').fadeOut();
              }
          });
          $('#back-to-top').click(function() {
              $('#back-to-top').tooltip('hide');
              $('body,html').animate({
                  scrollTop: 0
              }, 800);
              return false;
          });
          $('#back-to-top').tooltip('show');
          var badgeUrl = 'http://habboo-a.akamaihd.net/c_images/album1584/';
          $.getJSON( 'http://habboemotion.com/api/badge', function( badges ) {
              $.each( badges.list, function( key, badge ) {
                  $('div#badges').append('<img src="'+badgeUrl+badge.code+'.gif" class="thumbnail aleft" alt="Badge" data-toggle="tooltip" data-placement="top" title="'+badge.name+' - '+badge.desc+'">');
                  return (key !== 11);
              });
          });
          $.getScript('https://platform.twitter.com/widgets.js', function() {

          });
          $.getScript('http://habbfinity.ca/forum/external.php?type=js', function() {
              var str = "";
              for (x = 0; x < 4; x++) {
                  str += "<a href=\"http://habbfinity.ca/forum/showthread.php?t="+threads[x].threadid+"\" target=\"_blank\">"+threads[x].title+"</a> <br>(Posted By: "+threads[x].poster+")<br><br />";
              }
              $("#habbfinity_forum").html(str);
              console.log(str);
          });
      }
      $(document).ready(function() {
        $.ajax({
            url: '<?php echo $page; ?>.php',
            success: function(content) {
                $("#contfill").html(content);
                history.pushState(null, '', '<?php echo $page; ?>');
                homePageInit();
            }
        });
        $('#home').on("click", function(event) {
            $.ajax({
                url: 'home.php',
                success: function(content) {
                    $("#contfill").html(content);
                    history.pushState(null, '', 'home');
                    homePageInit();
                }
            });
            event.preventDefault();
        });
        $('#about').on("click", function(event) {
            $.ajax({
                url: 'about.php',
                success: function(content) {
                    $("#contfill").html(content);
                    history.pushState(null, '', 'about');
                    homePageInit();
                }
            });
            event.preventDefault();
        });
        $('#badges').on("click", function(event) {
            $.ajax({
                url: 'badges.php',
                success: function(content) {
                    $("#contfill").html(content);
                    history.pushState(null, '', 'badges');
                    homePageInit();
                }
            });
            event.preventDefault();
        });
      });
    </script>
  </body>
</html>
  • 写回答

1条回答 默认 最新

  • dongweihuan8832 2018-07-12 20:21
    关注

    After discussing in chat, the solution was to remove the RewriteRule ^badges/([0-9]+)/?$ badges.php?id=$1 [L] from the htaccess. Any url that doesn't have a .php renders only the content portion of #contfill.

    We then needed to modify the url the ajax uses in index.php, to convert the route from '/badges/324' to '/badges.php?id=324'

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 暴力法无法解出,可能要使用dp和数学知识
  • ¥15 wpf通过绑定控件自身的值,来实现背景颜色的切换
  • ¥15 CDH6.3 运行hive -e hive -e "show databases;"报错:hive-env.sh:行24: hbase-common.jar: 权限不够
  • ¥15 SSRS制作的报表打开报错,无法正常显示网页
  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系