首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Stack Overflow如何取代State?

Stack Overflow如何取代State?
EN

Stack Overflow用户
提问于 2013-06-09 02:58:05
回答 3查看 141关注 0票数 4

我是mac用户,从不使用IE。但是昨天在工作的时候,我去了stack overflow,并使用IE9在浏览器中输入了这段代码。

代码语言:javascript
复制
http://stackoverflow.com/questions/824349

他们在不刷新页面的情况下将URL替换为此URL...

代码语言:javascript
复制
http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page

我简直不敢相信我所看到的。你知道堆栈溢出是如何在不支持它的浏览器上利用模拟历史API的替换状态的功能的吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-09 03:00:44

它们实际上通过301重定向来重定向用户。查看标题:

代码语言:javascript
复制
GET /questions/824349 HTTP/1.1
Host: stackoverflow.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
[...]

HTTP/1.1 301 Moved Permanently
Cache-Control: public, max-age=60
Content-Type: text/html
Expires: Sat, 08 Jun 2013 19:00:05 GMT
Last-Modified: Sat, 08 Jun 2013 18:59:05 GMT
Location: /questions/824349/modify-the-url-without-reloading-the-page
Vary: *
X-Frame-Options: SAMEORIGIN
Date: Sat, 08 Jun 2013 18:59:05 GMT
Content-Length: 0
票数 9
EN

Stack Overflow用户

发布于 2013-06-09 03:03:26

这是一个301 Moved Permanently重定向,也就是说它是在服务器端完成的。你看不到刷新,因为浏览器没有打开第一个URL,它会立即重定向到第二个URL。

这是在chrome的控制台上的结果。

票数 3
EN

Stack Overflow用户

发布于 2013-06-09 03:11:19

如何以同样的方式实现301重定向也是如此。

(假设有一个名为questions的表,其中包含列idtitle)

(注意:对于每个页面视图,可能也会大量使用SO的Memcached,而不是DB访问,但这是另一个主题。)

对于URL:

代码语言:javascript
复制
http://stackoverflow.com/questions/824349

您的.htaccess将以questions.php?id=123&sef=abc-def格式重写URL

代码语言:javascript
复制
RewriteRule ^/questions/([0-9]+)/?([\w\-]*)$ /question.php?id=$1&sef=$2

您的question.php脚本

代码语言:javascript
复制
<?php
// Get the posted id (as int to prevent sql injection)
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

// Get the posted search-engine-friendly title string (if any)
$sef = isset($_GET['id']) ? $_GET['sef'] : '';

// Connect to the database
mysqli_connect(...);

// Get the question with the provided id
$result = mysqli_query("SELECT * FROM questions WHERE id = {$id}");

// If a question was found
if ($row = mysqli_fetch_assoc($result)) {
    // Find the SEF title for the question (lowercase, replacing 
    // non-word characters with hyphens)
    $sef_title = strtolower(preg_replace('/[^\w]+/', '-', $row['title']);

    // If the generated SEF title is different than the provided one,
    if ($sef_title !== $sef) {
        // 301 the user to the proper SEF URL
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: http://stackoverflow.com/question/{$id}/{$sef_title}");
    }
} else {
    // If no question found, 302 the user to your 404 page
    header("Location: http://stackoverflow.com/404.php");
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17002804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档