【问题标题】:How provide results based on the query results in a url?如何根据 url 中的查询结果提供结果?
【发布时间】:2010-09-17 02:53:51
【问题描述】:

是否有一个 javascript 解决方案来读取 url,从中创建一个字符串,并根据结果构建一个 if 语句?有谁知道教程或可以为我提供一些有关如何完成此操作的提示。

更具体地说,我正在尝试根据搜索结果执行此操作。所以.. 例如,网址是这样的:

http://www.site.com/catalogsearch/result?q=asdf&kw=asdf&x=0&y=0

根据 Daniels 的回复,我正在尝试这个,但没有运气:

if (window.location.search ==='?q=asdf') {
alert("You searched for asdf");
}

【问题讨论】:

  • 你能...更具体一点吗?预期的输入/输出?意图?你试过什么?
  • 我正在尝试使用 Daniels 的答案想出一些东西,但还没有运气。具体来说,我正在尝试根据搜索属性的结果编写条件语句。
  • function getUrlParam(param) { param = param.replace(/([[](){}*?+^$.\\|])/g, "\\$1"); var regex = new RegExp("[?&]" + param + "=([^]*)"); var url = decodeURIComponent(window.location.href); var match = regex.exec(url);返回匹配?匹配[1]:“”; } 变量参数 = getUrlParam("q"); if (param == "asdf") { alert(param); }

标签: javascript


【解决方案1】:

您可以使用 window.location 对象获取 URL 或其部分。

例如,考虑以下 URL:

http://www.google.com:80/search?q=devmo#test

这些是window.location 对象的标准属性,以及您将从上述 URL 获得的值:

property   | value
-----------+-----------------------------------------------------
hash       | #test
host       | www.google.com:80
hostname   | www.google.com
href       | http://www.google.com:80/search?q=devmo#test
pathname   | /search
port       | 80
protocol   | http:
search     | ?q=devmo

例如,如果要检查路径名,可以执行以下操作:

if (window.location.pathname === '/search') {
   // do something
}

【讨论】:

  • +1,但我建议不要在示例 url 中使用路径 /search,因为它与属性“搜索”不明确。
【解决方案2】:

这个怎么样

var str = window.location.href; 
if(str.indexOf("http") > - 1){
 //ah an if statment!
alert("url has http");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    相关资源
    最近更新 更多