Javascript-форум (https://javascript.ru/forum/)
-   Ваши сайты и скрипты (https://javascript.ru/forum/project/)
-   -   history рассширение для браузеров не поддерживающих pushState, replaceState (https://javascript.ru/forum/project/21077-history-rassshirenie-dlya-brauzerov-ne-podderzhivayushhikh-pushstate-replacestate.html)

devote 04.11.2013 23:53

Mateus,
вам просто нужно переписать /js/main.php на систему делегирования вместо обычного навешивания событий на элементы.

Mateus 05.11.2013 00:18

Можно, пожалуйста, поподробней?

devote 05.11.2013 01:07

Цитата:

Сообщение от Mateus
Можно, пожалуйста, поподробней?

примерно так:
<?php
    header("Content-Type: application/javascript");
?>
$(function(){

    // keep a reference to the query processor, so you can stop a query if necessary
    var xhr;

    function loadContent(url, push) {

        // previous operation interrupt request
        if (xhr) xhr.abort();

        var
            fragmentsUrl = url.split("?"),
            reqUrl = fragmentsUrl.shift();

        // ask for new data
        xhr = $.ajax({
            url: "<?php echo _LINK_PATH;?>ajax/core.php" + (fragmentsUrl.length ? "?" + fragmentsUrl.join("?") : ""),
            data: {"action": "page", "url": reqUrl},
            type: "post",
            dataType: "json",
            success: function(data, textStatus, xhr) {
                if (data.status == 1) {

                    // change the content
                    $("#dynamic_content").html(data.page.template);

                    // iterate through all the tags with the name script
                    $("script").each(function(){

                        // looking for a modular script
                        if (/(.*)<?php echo str_replace('/', '\\/', _LINK_PATH );?>js\/jscore.php\?module(.*)$/i.test(this.src)) {
                            var parent = this.parentNode;

                            // remove the script found to free up memory
                            parent.removeChild( this );
                            // Create a new script
                            var script = document.createElement('script');
                            script.type = "text/javascript";
                            script.async = "async";
                            script.src = "<?php echo _LINK_PATH;?>js/jscore.php?module=" + data.page.module;

                            // load it for execution
                            parent.appendChild(script);

                            return false;
                        }
                    });

                    if (data.page.title) {
                        document.title = data.page.title;
                    }

                    if (push) {
                        // replace the link in your browser
                        history.pushState(null, null, url);
                    }
                }
            },
            complete: function(xhr, textStatus) {
                //alert(xhr.responseText);
            },
            error: function(xhr, textStatus) {
            }
        });
    }

    $(window).on('popstate', function(e){
        /*
        * mind you, this is the only difference when working with the library,
        * Because the object document.location not be rebooted, so
        * History library returns generated by "location" object inside
        * Object window.history, so get it out of the "history.location".
        * For browsers support "history.pushState" get
        * Shaped object "location" with the usual "document.location".
        */
        var loc = history.location || document.location;
        // load the desired content
        loadContent(loc.href);
    });

    $(document).on('click', 'a.ajax', function(e) {
        if (window.history.pushState) {
            var href = $(e.target).closest('a').attr('href');
            href && loadContent(href, true);
            e.preventDefault();
        }
    });

    // if the link has a class of 'external' means to open it in another browser tab
    $(document).on('click', 'a.external', function(e) {
        var href = $(e.target).closest('a').attr('href');
        href && window.open(this.href);
        e.preventDefault();
    });
});

devote 16.05.2014 19:13

Давно не писал про обновления, но что-то новое уже в нее внес... Так же появилась поддержка AMD, ну и что-то еще... Правки всякие и т.д.

devote 19.05.2014 17:00

Привет All

Создал клон своего демо-сайта, без серверного языка. Смотрим тут http://devote.github.io/demos/history/

shuff22 06.08.2015 00:40

Привет, devote. На примере вашего демо-сайта пытаюсь сделать так, чтоб страницы можно было загружать не только из template, но и из template/pages

файл test.php находится в templates/pages

В menu_top.php я прописываю ссылку

<a class="ajax" href="<?php echo _LINK_PATH;?>pages/test">test</a>


В файле includes/modules.php пишу

<?php

	$modules = array(

		"pages/test" => array(
			"title" => "Test",
			"templates" => array(
				"pages/test.php",
			),
		),
	);

	$modules[""] = $modules["home"];

?>


Но при клике ничего не происходит. Подскажите пожалуйста, как мне добиться желаемого результата?

devote 06.08.2015 09:07

shuff22,
привет, на самом деле я давно уже не открывал этот демо пример да и не помню где он у меня валяется. А вообще рекомендую дебажить. А вообще имя модуля не может содержать что-то более одного подуровня. Попробуй вместо
"pages/test" => array(
написать это:
"pages" => array(
а потом тебе нужно будет обрабатывать переменную она покажет все параметры, что и как.. вообщем дерзай.

Mikhail1989 13.08.2015 10:40

devote, здравствуйте. Есть вопрос по html5 history api.
Использую history.js. При переходе по ссылкам которые находятся на том же уровне все хорошо, т.е.index.html, one.html, two.html. Если же пытаюсь перейти по ссылке на втором уровне, например, papka/three.html, то переход идет почему-то на papka/papka/three.html. А такого файла соответственно нет. В чем может быть ошибка?


Часовой пояс GMT +3, время: 00:46.