将javascript对象转换为URL参数

时间:2014-03-27 04:32:29

标签: javascript jquery url

我意识到,从根本上说,我可能会以错误的方式解决这个问题,所以我愿意向正确的方向努力。

我正在尝试使用HipChat API向类似的房间发送通知:

https://www.hipchat.com/docs/api/method/rooms/message

我正在尝试使用js对象的参数在示例中构建URL,所以基本上我正在尝试转换它:

var hipChatSettings = {
            format:"json",
            auth_token:token,
            room_id: 1,
            from: "Notifications",
            message: "Message"
        }

对此:

https://api.hipchat.com/v1/rooms/message?format=json&auth_token=token&room_id=1&from=Notifications&message=Message

6 个答案:

答案 0 :(得分:43)

您应该查看jQuery.param function



var params = { width:1680, height:1050 };
var str = jQuery.param( params );
console.log(str);

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

答案 1 :(得分:40)

Object.keys(hipChatSettings).map(function(k) {
    return encodeURIComponent(k) + "=" + encodeURIComponent(hipChatSettings[k]);
}).join('&')
// => "format=json&auth_token=token&room_id=1&from=Notifications&message=Message"

警告:新的JavaScript。如果您希望它能够在古人身上工作,请将其填充或重写为for

答案 2 :(得分:12)

这样的事可能适合你

var str = "?" + Object.keys(hipChatSettings).map(function(prop) {
  return [prop, hipChatSettings[prop]].map(encodeURIComponent).join("=");
}).join("&");

// "?format=json&auth_token=token&room_id=1&from=Notifications&message=Message"

如果您不能依赖ECMAScript 5,则可以使用简单的for循环

var pairs = [];

for (var prop in hipChatSettings) {
  if (hipChatSettings.hasOwnProperty(prop)) {
    var k = encodeURIComponent(prop),
        v = encodeURIComponent(hipChatSettings[prop]);
    pairs.push( k + "=" + v);
  }
}

var str = "?" + pairs.join("&");

答案 3 :(得分:0)

ES6版本,可以真正使用数组嵌套对象

  

encodeURI(getUrlString({a:1,b:[true,12.3,“ string”]})))

getUrlString (params, keys = [], isArray = false) {
  const p = Object.keys(params).map(key => {
    let val = params[key]

    if ("[object Object]" === Object.prototype.toString.call(val) || Array.isArray(val)) {
      if (Array.isArray(params)) {
        keys.push("")
      } else {
        keys.push(key)
      }
      return getUrlString(val, keys, Array.isArray(val))
    } else {
      let tKey = key

      if (keys.length > 0) {
        const tKeys = isArray ? keys : [...keys, key]
        tKey = tKeys.reduce((str, k) => { return "" === str ? k : `${str}[${k}]` }, "")
      }
      if (isArray) {
        return `${ tKey }[]=${ val }`
      } else {
        return `${ tKey }=${ val }`
      }

    }
  }).join('&')

  keys.pop()
  return p
}

答案 4 :(得分:0)

晚了跳舞,但是我很喜欢这个简短的故事:

exports.doSome = functions.database.ref('/users/{userId}/dataSets/{dataSetNo}').onWrite(
 async (change, context) => {
  const userId = context.params.userId;
  const yearNo = context.params.yearNo;
  const weekNo = getWeekNo();
  var ref = change.after.ref.root.child('users');
  var dataPath = `${userId}/weeklyTriggers/${dataSetNo}/${weekNo}/data`;

  var foo={};
  foo[dataPath] = "Some data";

  return ref.update(foo);
});

答案 5 :(得分:-7)

尝试使用此方法:

 public static SerializeParams<T>(Datos: T): string {
            var keys = Object.keys(Datos);
            var stringParams: string = "?";
            for (var i in keys) {
                var name = keys[i];
                if (i == 0)
                    stringParams += name + "=" + JSON.stringify(Datos[name]);
                else
                    stringParams += "&" + name + "=" + JSON.stringify(Datos[name])
            }
            return stringParams;
        };