【问题标题】:How to organize country/state/city browsing in MVC如何在 MVC 中组织国家/州/城市浏览
【发布时间】:2011-12-30 19:43:53
【问题描述】:

我正在创建一个基于 ajax 的网站,其中包含国家/州/城市浏览界面。出于 SEO 的目的,我想在 URL 中包含国家/州/城市的名称。例如,url 可能包含其他变量,类似于:

 http://www.website.com/browse#!USA/NY/Albany
 http://www.website.com/browse#!USA/NY/Albany?Category=sports

我需要通过 AJAX 将此功能融入到 MVC 框架(特别是 CodeIgniter)中。我不确定如何组织主要组件,特别是控制器、AJAX 处理程序和可能的库类。是否有标准或最佳实践方法?

【问题讨论】:

    标签: php ajax codeigniter codeigniter-routing


    【解决方案1】:

    是的,Google 写了一些关于这个主题的好东西,特别是使用片段标识符维护 ajax 应用程序状态: http://code.google.com/web/ajaxcrawling/docs/specification.html

    这是我在 index.php 文件中放置的一些代码来处理这个问题:

    // Special handler for ajax partials ("AHAH" paradigm)
    if (isset($_GET['_escaped_fragment']))
    {
        // Grab just the fragment
        $fragment = $_GET['_escaped_fragment'];
    
        // See if we have GET parameters to extract from the fragment
        if (FALSE !== ($p = strpos($fragment, '?')))
        {
            // Make sure to save additional GET parameters
            $additional_params = array_diff_key($_GET, array('_escaped_fragment' => 1));
    
            // Parse the querty string
            parse_str(substr($fragment, $p+1), $_GET);
    
            // Add the originals back in
            $_GET = array_merge($_GET, $additional_params);
    
            // The beginning part of the fragment is the base URI
            $fragment = substr($fragment, 0, $p);
        }
    
        // Otherwise, clear the $_GET array
        else
        {
            $_GET = array();
        }
    
        $_SERVER['PATH_INFO']   = $fragment;
        $_SERVER['REQUEST_URI'] = $fragment;
    
        // Add a constant for use throughout the app
        define('IS_FRAGMENT', 1);
    }
    defined('IS_FRAGMENT') OR define('IS_FRAGMENT', 0);
    

    方法是这样的:

    1) 如果是 ajax 请求且 IS_FRAGMENT == 1,则仅显示填充前端更改所需的部分结果

    2) 否则,假设它是搜索引擎或直接页面加载。显示完整的页面。

    您不必仅为 ajax 请求创建单独的端点。扩展 Output 类以提供请求格式的响应可能会更好。这样更 RESTful。

    对于可以处理它的浏览器,利用 HTML5 History API 并为其他浏览器回退到 onhashchange 事件也是一种很好的做法。

    更多提示:

    使用“#!”指示 ajax 触发的内容更改,而不仅仅是一个“#”。您可能在某些时候想要使用片段提供的默认锚功能(但感叹号是“安全的”,因为您可能没有以该特定字符开头的元素 ID)。

    我还建议使用绝对 URI(即 #!/USA/NY/Albany),因为这样更容易在您的 ajax 部分加载机制中保持一致。

    此外,如果有人在 URL 中使用 ajaxed-fragment 重新加载页面,如果您不只是执行 window.location.href = '...' 来重新加载页面,它可能会变得非常混乱。那时你会遇到各种后退/前进问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-20
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 2014-09-08
      • 1970-01-01
      相关资源
      最近更新 更多