3

I am trying to write a function like this:

if ( document.url!= 'search.php') {
    window.location = 'search.php' 
}

This is not working; it seems I may need to check if URL string contains 'search.php' - or is there another way I can do this check?

4

2 回答 2

4

听起来您正在寻找indexOf. 请注意,它不是document.url,而是document.URL

if (document.URL.indexOf('search.php') == -1) {
    window.location = 'search.php';
}

注意:这也将匹配以下内容:

http://www.domain.com/search.php
http://www.domain.com/index.php?page=search.php&test
http://www.domain.com/search.php/non-search。 php
http://www.domain.com/non-search.php#search.php

额外说明:你为什么这样做?如果人们禁用了 javascript,他们将永远不会被转发。也许您正在搜索301or302标头?

于 2013-07-28T20:34:56.910 回答
2

我总是用这个。

if (window.location.href != 'search.php') {//get the current url
        window.location.href = 'search.php' //redirect
    }

试试这些

- alert(document.URL)

- alert(Window.location.href)

- alert(document.location.href)

- alert(window.location.pathname)

用于创建带有链接的下拉列表 - :将其放入 ajax 的成功部分

            var data=JSON.parse(xmlhttp.responseText);
            var alldata;
            for(var  i=0;i< data.length;i++)
            {
                alldata += "<a id='some_id' onclick='myFunction(this.id);' href='whatever#' class='link'>"+data[i][0]+"</a><hr>";
            }
            //data[i][0]-->this depends on your json text.
       document.getElementById('your_input_field_id or div_id').innerHTML = alldata;
于 2013-07-28T20:44:35.710 回答