【问题标题】:Get GET variables from url using JavaScript jQuery使用 JavaScript jQuery 从 url 获取 GET 变量
【发布时间】:2018-05-14 19:53:15
【问题描述】:

我想使用 jquery 从 url 中读取一个 GET 变量

域名是这样显示的

http://example.com/p/kT2Rnu35

原来是:

http://example.com/php/page.php?id=kT2Rnu35

我想使用 jQuery 从域为 http://example.com/p/kT2Rnu35 的页面中获取该 ID

我尝试了 window.location 和其他在堆栈溢出时发现的功能,但没有任何效果。是因为我正在使用 htaccess 更改网址吗?

【问题讨论】:

    标签: javascript php variables get


    【解决方案1】:

    window.location.href会给你带参数的url

    从那里只需使用 .split 将其分开

    【讨论】:

      【解决方案2】:

      const getParameterByName = (name, url) => {
        const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);
        const results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
      };
      
      let url = 'https://website.com/abc?id=123';
      
      console.log(getParameterByName('id', url));
      
      // For url like this `http://example.com/p/kT2Rnu35` simply get the last token after `/`
      
      url = 'http://example.com/p/kT2Rnu35';
      let id = url.substring(url.lastIndexOf('/') + 1);
      console.log(id);

      【讨论】:

      • 但我想直接从页面example.com/p/12345678而不是从原始页面获取变量
      • @nadhirdz 更新我对该案例的回答
      猜你喜欢
      • 1970-01-01
      • 2012-07-02
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 2010-12-29
      • 2015-01-18
      • 1970-01-01
      相关资源
      最近更新 更多