是的,谷歌在这个主题上写了一些好东西,特别是使用片段标识符维护 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 = '...' 来重新加载页面,它可能会变得非常混乱。那时你会遇到各种后退/前进问题。