2012-04-05 50 views
0

如何在JavaScript中添加一些内容,以检查某个网站上某个人的网站地址,然后重定向到网站上的某个页面,如果找到了匹配项?例如...在javascript中检查某些url?

我们要检查的字符串,将mydirectory,所以如果有人去mysite.com/mydirectory/anyfile.php甚至mysite.com/mydirectory/index.php的JavaScript会那么他们的网页/ URL重定向到mysite.com/index.php因为它在URL mydirectory,怎么能我这样做使用JavaScript?

回答

0

如果我理解正确的问题,那么它是相当简单的,并且可以使用document.URL

var search = 'mydirectory'; // The string to search for in the URL. 
var redirect = 'http://mysite.com/index.php' // Where we will direct users if it's found 
if(document.URL.substr(search) !== -1) { // If the location of 
    // the current URL string is any other than -1 (doesn't exist) 
    document.location = redirect // Redirect the user to the redirect URL. 
} 

使用document.URL您可以检查URL什么来实现,但你可能想看看使用Apache的mod_rewrite之类的东西来重定向用户,甚至在他们加载页面之前。

+0

你在if条件中有一个额外的'='。 – neo108 2012-04-05 00:27:15

+1

使用完全相等(===和!==)来避免(0 == false)或(-1 =='-1')返回true这样的问题会更好。它不会影响这种情况,但它也不会造成伤害。 http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – 2012-04-05 00:35:04

+0

感谢@DanPrince。我学到了新东西! – neo108 2012-04-05 00:44:33

0

退房window.location,特别是it's properties and methods。您会对pathname属性(可以将其拆分为/)和href属性感兴趣(部分属性)以更改页面。

这是所有假设的JavaScript服务的第一个地方;所以我假设anyfile.phpindex.php都会导致JS被服务,而不是一些“通用404”消息。