【问题标题】:What is the proper URL syntax to define a location object and a URL parameter?定义位置对象和 URL 参数的正确 URL 语法是什么?
【发布时间】:2016-02-20 10:13:31
【问题描述】:

我见过很多例子,但没有一个具有这种特定设置。我的 URL 当前有一个位置对象,它通过 jquery 打开一个表单: http://blah.com/contact.cfm?show_sales

$(document).ready(function(){
    if (window.location.search == "?show_sales") {
        $('#sales_form').show();
    };

我还希望在 URL 中包含一个参数: http://blah.com/contact.cfm?item=4445555

我尝试了两者的组合,但我不知道包含两者的正确语法。我尝试过的一切都不会激活 jquery。

那么,这个 URL 的正确语法是什么?

http://blah.com/contact.cfm?show_sales&item=4445555

(这是一个不起作用的例子)

【问题讨论】:

  • http://blah.com/contact.cfm?show_sales&item=4445555 对向查询字符串添加多个键/值对是正确的。你的 JavaScript 只是没有正确解析。从location.search 中删除前导?,然后将其拆分为&
  • 您可以拆分location.search 或使用RegExp 来隔离查询字符串字段和值

标签: javascript jquery html forms url


【解决方案1】:

网址格式正确。您应该对代码进行一些更改:

$(document).ready(function(){
    if (window.location.search.indexOf("?show_sales")!=-1) {
        $('#sales_form').show();
    };

window.location.search 将返回 show_sales&item=4445555

【讨论】:

  • 当我阅读它时,这句话基本上是在说“如果“?show_sales”的索引不等于-1,则显示表单。您能解释一下为什么或如何涉及 -1 索引吗?
【解决方案2】:

你可以使用拆分:

var url = "http://blah.com/contact.cfm?show_sales&item=4445555";

var query = url.split("?")[1];

var params = query.split("&");

console.log(params); 


// params[0] = "show_sales"
// params[1] = "item=444555" and you can split again

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2013-07-03
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多