使用JavaScript将参数添加到URL [英] Adding a parameter to the URL with JavaScript

查看:168
本文介绍了使用JavaScript将参数添加到URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用AJAX调用的Web应用程序中,我需要提交请求,但在URL的末尾添加一个参数,例如:

In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:

原始网址:


http ://server/myapp.php?id = 10

生成的网址:


http://server/myapp.php?id = 10 & enabled = true

寻找解析网址的JavaScript函数查看每个参数,然后添加新参数或更新值(如果已存在)。

Looking for a JavaScript function which parses the URL looking at each parameter, then adds the new parameter or updates the value if one already exists.

推荐答案

您的基本实现我需要适应看起来像这样:

A basic implementation which you'll need to adapt would look something like this:

function insertParam(key, value)
{
    key = encodeURI(key); value = encodeURI(value);

    var kvp = document.location.search.substr(1).split('&');

    var i=kvp.length; var x; while(i--) 
    {
        x = kvp[i].split('=');

        if (x[0]==key)
        {
            x[1] = value;
            kvp[i] = x.join('=');
            break;
        }
    }

    if(i<0) {kvp[kvp.length] = [key,value].join('=');}

    //this will reload the page, it's likely better to store this until finished
    document.location.search = kvp.join('&'); 
}

这大约是正则表达式或基于搜索的解决方案的两倍,但是完全取决于查询字符串的长度和任何匹配的索引

This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match

我为了完成而进行基准测试的慢正则表达式方法(约+ 150%慢)

the slow regex method I benchmarked against for completions sake (approx +150% slower)

function insertParam2(key,value)
{
    key = encodeURIComponent(key); value = encodeURIComponent(value);

    var s = document.location.search;
    var kvp = key+"="+value;

    var r = new RegExp("(&|\\?)"+key+"=[^\&]*");

    s = s.replace(r,"$1"+kvp);

    if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};

    //again, do what you will here
    document.location.search = s;
}

这篇关于使用JavaScript将参数添加到URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆