php включает содержимое не загружается, возможная проблема с хеш-тегом / адресом - PullRequest
0 голосов
/ 22 ноября 2011

http://www.queness.com/post/328/a-simple-ajax-driven-website-with-jqueryphp

Я пытаюсь заставить работать вышеуказанный скрипт, но с некоторыми изменениями.Мне нужно, чтобы содержимое загружалось как php, а не как строка html.Моя главная проблема сейчас заключается в том, что я не думаю, что код перенаправляет на нужную страницу, поэтому нет нового содержимого.*

JavaScript:

<script type="text/javascript">

    $(document).ready(function () {

    //Check if url hash value exists (for bookmark)
    $.history.init(pageload);   

    //highlight the selected link
    $('a[href=' + document.location.hash + ']').addClass('selected');

    //Seearch for link with REL set to ajax
    $('a[rel=ajax]').click(function () {

        //grab the full url
        var hash = this.href;

        //remove the # value
        hash = hash.replace(/^.*#/, '');

        //for back button
        $.history.load(hash);   

        //clear the selected class and add the class class to the selected link
        $('a[rel=ajax]').removeClass('selected');
        $(this).addClass('selected');

        //hide the content and show the progress bar
        $('#content').hide();
        $('#loading').show();

        //run the ajax
        getPage();

        //cancel the anchor tag behaviour
        return false;
    }); 
});


function pageload(hash) {
    //if hash value exists, run the ajax
    if (hash) getPage();    
}

function getPage() {

    //generate the parameter for the php script
    var data = 'page=' + document.location.hash.replace(/^.*#/, '');
    $.ajax({
        url: "loader.php",  
        type: "GET",        
        data: data,     
        cache: false,
        success: function (html) {  

            //hide the progress bar
            $('#loading').hide();   

            //add the content retrieved from ajax and put it in the #content div
            $('#content').html(html);

            //display the body with fadeIn transition
            $('#content').fadeIn('slow');       
        }       
    });
}

    </script>

Ответы [ 2 ]

1 голос
/ 22 ноября 2011

Вы уверены, что выбрали правильный путь?

case 'code' : $page = include($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'mysite/code.php'); break;
case 'design' : $page = include($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'mysite/design.php'); break;
case 'writing' : $page = include($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'mysite/writing.php'); break;

$ _ SERVER ['DOCUMENT_ROOT'] в разных средах может иметь косую черту или нет, поэтому будьте осторожны при добавлении файлов из $ _SERVER ['DOCUMENT_ROOT']

case 'code' : $page = include ($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'mysite/code.php'); break;
case 'design' : $page = include ($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'mysite/design.php'); break;
case 'writing' : $page = include ($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'mysite/writing.php'); break;
1 голос
/ 22 ноября 2011

include не возвращает ничего, кроме true / false, чтобы указать, что включает в себя успех / неудача.По сути это очень похоже на eval(), за исключением использования внешних файлов.Если ваши включенные страницы действительно генерируют вывод, вам нужно сначала захватить его:

ob_start();
include('somepage.php');
$content = ob_get_clean();

return $content;

Или, если включения генерируют контент и сохраняют его в переменной, то:

include('somepage.php');
echo $whatever_var_that_somepage_php_stored_the_content_in;
...