【问题标题】:Managing queries with URI.js使用 URI.js 管理查询
【发布时间】:2015-10-07 05:29:57
【问题描述】:

我的目标是能够管理和修改 URL 中的查询参数。我决定试一试URI.js

页面第一次加载时,已经有一个参数:http://localhost:3000/football?game=This-Game。我想要做的是附加参数,如http://localhost:3000/football?game=This-Game&foo=bar&fiz=buzz

我不太清楚如何使用 URI.js 来做到这一点,同时保留参数的第一部分。我想我可能不得不在页面加载时将第一个参数拉入一个对象,然后重置它,但希望有一种更简单的方法。

在尝试 URI.js 之前,我使用 pushState 并抓取了当前的 window.location 加上我想要添加的任何参数,形成一个字符串,并将其推送到 URL

if (typeof (history.pushState) != 'undefined') { var obj = { Title: title, Url: url }; history.pushState(obj, obj.Title, obj.Url); }

我想仍然使用 pushState(因为我认为这是唯一的方法,虽然 URI.js 文档并没有过多谈论它),但基本上有一个参数对象,我可以添加、删除等. 只要我愿意,它就会自动更新 URL。

我目前正在使用这段代码,但结果是http://localhost:300/game=ISC-World-Tournament&foo=bar(缺少第一个参数)。

var url = new URI;
url.addQuery({foo: 'bar'})

if (typeof (history.pushState) != 'undefined') {
    var obj = { Title: 'test', Url: url._parts.query };
    history.pushState(obj, obj.Title, obj.Url);
}

总之,我认为我在正确的轨道上,但希望有一种简单的方法来管理参数。

【问题讨论】:

    标签: javascript url uri pushstate


    【解决方案1】:

    您可以使用setQuery 方法更新现有参数并添加新参数。

    来自链接:

    var uri = new URI("?hello=world");
    uri.setQuery("hello", "mars"); // returns the URI instance for chaining
    // uri == "?hello=mars"
    
    uri.setQuery({ foo: "bar", goodbye : ["world", "mars"] });
    // uri == "?hello=mars&foo=bar&goodbye=world&goodbye=mars"
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2016-07-02
      • 2015-01-30
      • 2013-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      相关资源
      最近更新 更多