3

js请求接口带数据-拼接URL字符串

 2 years ago
source link: https://www.geekjc.com/post/5f1c3497889b434ceef7500d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
关注本站公众号获取最新福利

js请求接口带数据-拼接URL字符串

时间: 07/25/2020作者: 一颗小草浏览量: 914

项目开发中,经常会遇到http请求(特别是get请求)或者跳转页面需要拼接URL请求字符串,而经常性的思维就是利用“+”进行字符串拼接:

var baseUrl = 'www.google.com'
var a = 1, b = 'request', c = true
var finalUrl = baseUrl + '?a=' + a + '&b=' + b + '&c=' + c

这种方法看起来丑陋笨拙,最不优雅。 然推荐一种写法,也非常适用于项目开发,那就是将对象形式转化为URL请求字符串的代码提取成为一个工具函数,需要的时候调用就可以了。

/**
 * 拼接对象为请求字符串
 * @param {Object} obj - 待拼接的对象
 * @returns {string} - 拼接成的请求字符串
 */
 Function encodeSearchParams(obj) {
  var params = []

  Object.keys(obj).forEach((key) => {
    let value = obj[key]
    // 如果值为undefined我们将其置空
    if (typeof value === 'undefined') {
      value = ''
    }
    // 对于需要编码的文本(比如说中文)我们要进行编码
    params.push([key, encodeURIComponent(value)].join('='))
  })
  return params.join('&')
}

然后使用的姿势:

var obj = {
    a: 1,
    b: 'request',
    c: true,
}
var finalUrl = `${baseUrl}?${encodeSearchParams(obj)}`
关注下面的标签,发现更多相似的文章

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK