问题
I try to use jquery pjax to load my contents in a div. this works fine, but if i reload the page i have no content. i think i need to put the page content in the else{ part, but i don't want to set the whole html in a php variable. how to fix this?
index.php:
<?php
$title = 'Home';
if(isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX'] == 'true'){ ?>
<div id="content">
<h1>home</h1>
</div>
<?php echo "<title>{$title}</title>";
}else{
include 'wrapper.php';
}
?>
wrapper.php:
<ul class="nav navbar-nav" style='margin-left:20px;'>
<li><a href='index.php' data-pjax='content'>Home</a></li>
<li><a href='page1.php' data-pjax='content'>Demo 1</a></li>
<li><a href='page2.php' data-pjax='content'>Demo 2</a></li>
</ul>
<div id="content"></div>
The JS:
$(document).ready(function() {
$(document).pjax('a[data-pjax]', '#content', {
fragment: '#content'
});
});
page1.php
<?php if(isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX'] == 'true'){ ?>
<div id="content">
<h1>Page 1</h1>
</div>
<?php } else{ include 'wrapper.php';} ?>
page2.php
<?php if(isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX'] == 'true'){
?>
<div id="content">
<h1>Page 2</h1>
</div>
<?php }else{
include 'wrapper.php';
}
?>
回答1:
You are only including the wrapper.php when the page is requested without PJAX (== the normal way). In wrapper.php the content is empty.
In wrapper.php you should include the correct page if the request origin is not PJAX:
First of all you should rename some files. Use index.php as the main lay-out file (what you intended to do with wrapper). Add the p as query param (which can be read true $_GET
in PHP) to load pages when clicking links.
Create a file home.php which will be the default page loaded in #content
at index.php.
index.php
<ul class="nav navbar-nav" style='margin-left:20px;'>
<li><a href='index.php' data-pjax='content'>Home</a></li>
<li><a href='index.php?p=1' data-pjax='content'>Demo 1</a></li>
<li><a href='index.php?p=2' data-pjax='content'>Demo 2</a></li>
</ul>
<div id="content">
<?php if(!isset($_SERVER['HTTP_X_AJAX'])) {
if(!isset($_GET['p'])) {
include('home.php');
}
else {
include('page'.$_GET['p'].'.php');
}
} ?>
</div>
This is very simple example. In live applications this should be done in another way to protect the script against certain attacks.
I'm guessing you are a starter. Please take a look at CodeIgniter. It is a framework which has a lot of ready-to-use functions. It has proven to be 'easy' to learn...
来源:https://stackoverflow.com/questions/32285243/jquery-pjax-with-php-no-content-at-reload