2020-04-01-building-rails-compatible-query-strings-in-javascript

栏目: IT技术 · 发布时间: 4年前

内容简介:TheWhat itI don't even remember where this comes from, I've written it for so many different projects I just copy it from the last one.
layout title date categories tags

post

Building Rails-compatible Query Strings in JavaScript

2020-04-01T13:57

javascript

query-string

javascript

functions

missing-libraries

rails

The MDN defines the URLSearchParams to help build query strings based on objects.

What it doesn't do, however, is build a Rails-compatible query string from a nested object, i.e., an object with properties that other objects, i.e. Object, Array, etc. This won't do anything if the parent object has a function property, but it's a pretty good implementation.

I don't even remember where this comes from, I've written it for so many different projects I just copy it from the last one.

The problem is that when given a params object like:

let params = {
    a: 27,
    b: "forty-two",
    c: [1, 2, 3, 5],
    d: { id: 2887, name: "Gillian" }
}

Passing this into URLSearchParams doesn't give a query string that Rails finds useful in parsing parameters up in the controller:

let qa = new URLSearchParams(params).toString()

yields: a=27&b=forty-two&c=1,2,3,5&d=d=%5Bobject+Object%5D which is really no good to Rails (doubt it would be good for express either, but that's not what this one's about).

So we need something a bit more on point:

function serializeObjectToRailsQueryString(params, prefix) {
  const query = Object.keys(params).map(key => {
     const value = params[key]

     if (params.constructor === Array) key = `${prefix}[]`
     else if (params.constructor === Object)
       key = prefix ? `${prefix}[${key}]` : key

     if (typeof value === "object")
       return serializeObjectToQueryString(value, key)
     else return `${key}=${encodeURIComponent(value)}`
   })

   return [].concat.apply([], query).join("&")
}

Passing that same params object above, yields the following:

"a=27&b=forty-two&c[]=1&c[]=2&c[]=3&c[]=5&d[id]=2887&d[name]=Gillian"

When the controller params method is called, it yields a AC::Parameters object of:

{
  a: 27,
  b: "forty-two",
  c: [1, 2, 3, 5],
  d: { id: 2887, name: "Gillian"}
}

just as we'd expect.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

引爆流行

引爆流行

[美] 马尔科姆·格拉德威尔 / 钱清、覃爱冬 / 中信出版社 / 2002-7 / 18.00元

马尔科姆·格拉德威尔以社会上突如其来的流行风潮研究为切入点,从一个全新的角度探索了控制科学和营销模式。他认为,思想、行为、信息以及产品常常会像传染病爆发一样,迅速传播蔓延。正如一个病人就能引起一场全城流感;如果个别工作人员对顾客大打出手,或几位涂鸦爱好者管不住自己,也能在地铁里掀起一场犯罪浪潮;一位满意而归的顾客还能让新开张的餐馆座无虚席。这些现象均属“社会流行潮”,它爆发的那一刻,即达到临界水平......一起来看看 《引爆流行》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具