JQuery BBQ не могу получить красивые URL;используя pushstate - PullRequest
1 голос
/ 05 апреля 2011

Спасибо.

URL выглядят так: http://mysite.com/#main=mysite.php%3Fid%3D108&main=mysite.php%3Fid%3D108

Я пытаюсь заставить их выглядеть так: http://mysite.com/#main=mysite.php?id=108&main=mysite.php?id=108

Вот код:

  $(function(){
      $('.bbq').each(function(){
        $(this).data( 'bbq', {
          cache: {
            '': $(this).find('.bbq-default')
          }
        });
      });

  // For all links inside a .bbq widget, push the appropriate state onto the
  // history when clicked.
      $('.bbq a[href^=#]').live( 'click', function(e){
        var state = {},

          // Get the id of this .bbq widget.
          id = $(this).closest( '.bbq' ).attr( 'id' ),

          // Get the url from the link's href attribute, stripping any leading #.
          url = $(this).attr( 'href' ).replace( /^#/, '' );

        // Set the state!
        state[ id ] = url;
        $.bbq.pushState( state );

        return false;
      });

  $(window).bind( 'hashchange', function(e) {

    // Iterate over all .bbq widgets.
      var that = $(this),

        // Get the stored data for this .bbq widget.
        data = that.data( 'bbq' ),

        // Get the url for this .bbq widget from the hash, based on the
        // appropriate id property. In jQuery 1.4, you should use e.getState()
        // instead of $.bbq.getState().
        url = $.bbq.getState( that.attr( 'id' ) ) || '';

      // If the url hasn't changed, do nothing and skip to the next .bbq widget.
      if ( data.url === url ) { return; }

      // Store the url for the next time around.
      data.url = url;

      // Remove .bbq-current class from any previously "current" link(s).
      that.find( 'a.bbq-current' ).removeClass( 'bbq-current' );

      // Hide any visible ajax content.
      that.find( '.bbq-content' ).children( ':visible' ).hide();

      // Add .bbq-current class to "current" nav link(s), only if url isn't empty.
      url && that.find( 'a[href="#' + url + '"]' ).addClass( 'bbq-current' );

      if ( data.cache[ url ] ) {
        // Since the widget is already in the cache, it doesn't need to be
        // created, so instead of creating it again, let's just show it!
        data.cache[ url ].show();

      } else {
        // Show "loading" content while AJAX content loads.
        that.find( '.bbq-loading' ).show();

        // Create container for this url's content and store a reference to it in
        // the cache.
        data.cache[ url ] = $( '<div class="bbq-item"/>' )

          // Append the content container to the parent container.
          .appendTo( that.find( '.bbq-content' ) )

          // Load external content via AJAX. Note that in order to keep this
          // example streamlined, only the content in .infobox is shown. You'll
          // want to change this based on your needs.
          .load( url, function(){
            // Content loaded, hide "loading" content.
            that.find( '.bbq-loading' ).hide();
          });
      }
    });
  })

            $(window).trigger( 'hashchange' );

});

Редактировать

Я должен был прояснить это: http://mysite.com/#main=page1.php?id=108&main2=page2.php?id=108 загрузка других страниц со строками.

1 Ответ

1 голос
/ 07 июля 2011

Вы запрашиваете красивые URL, но формат URL, который вы запрашиваете, далек от "красивого".

Вы просите, чтобы ваш URL выглядел так:

http://mysite.com/#main=page1.php?id=108&main2=page2.php?id=108

В основном ваш формат URL говорит мне, что вы находитесь на странице, которая ссылается на другой URL в своем собственном URL, и этот URL, на который он ссылается, сам ссылается на третий URL. Это очень сложная схема URL, которая может запутать ваших пользователей. Чего вы пытаетесь достичь с помощью этого?

Целью добавления компонентов к хешу URL на ajax-сайте таким образом является предоставление пользователю того, на что он может ссылаться или делать закладки. Спросите себя, помогут ли заданные вами параметры в этом.

Мне кажется, что вы можете достичь почти того же самого, просто набрав id=108 в своем хэше URL. Все остальное - пух, который пользователь не должен видеть в URL. Ваш код Javascript может перестраивать внутренние URL-адреса ajax без необходимости знать о них пользователя.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...