js将属性添加到url param对象

时间:2017-07-03 16:20:32

标签: javascript jquery

我有一个网址,我创建了以下方式:

53

以后是否有一种简单的方法可以将属性添加到属性对象: 我想要与此相同的结果:

curl 'https://cloudant-URL-bluemix.cloudant.com/mydb/_changes?feed=continuous&heatbeat=1000'

最好的解决方案是合并参数。与此类似(显然不起作用):

let forwardBaseUrl = 'https://www.usergems.com/api/gmail/info?' + $.params({
                event: 'Click forwarded link',
                email: btoa(userEmail),
                properties: {
                    forwardId: btoa(forwardId)
                }
            });

2 个答案:

答案 0 :(得分:1)

首先,实际的JQuery方法是 $.param() ,而不是$.params()

接下来,如果您将代码重构为" build" " params"对象并设置一个可以向对象添加属性的函数,然后您可以随时重新生成序列化结果:



var userEmail = "me@you.com";
var forwardId = "12345";

var props = {
    forwardId: btoa(forwardId)
};

var paramObj = {
  event: 'Click forwarded link',
  email: btoa(userEmail),
  properties: props
};

let forwardBaseUrl = 'https://www.usergems.com/api/gmail/info?' + $.param(paramObj);

console.log(forwardBaseUrl);

function changeProperties(prop, value, addRemove){
    if(addRemove){
      // Add new property to properties object
      props[prop] = value;
    } else {
      // remove property from properties object
      delete props[prop];
    }
}

// Add a new property to the params "properties" object:
changeProperties("forwardUrl", "http://google.at", true);

// Update serialized params
forwardBaseUrl = 'https://www.usergems.com/api/gmail/info?' + $.param(paramObj);

console.log(forwardBaseUrl);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var restObj = {
  url: 'https://www.usergems.com/api/gmail/info?'
  params: {
     event: 'Click forwarded link',
     email: 'asda',
     properties: {
        forwardId: btoa('asd')
     }
  },
  getUrl: function () {
    return this.url + $.param(this.params);
  }
}

//现在你可以改变params对象了 restObj.params.properties.anotherParam ='param';

//获取新网址 的console.log(restObjgetUrl。)