是的,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 = '...' 来重新加载页面,它可能会变得非常混乱。那时你会遇到各种后退/前进问题。