最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】JS中如何实现将字典变量去url的encode

JS crifan 3134浏览 0评论

希望在fetch的时候,把dict的json对象:

        body: {
          currTime: ‘2017-07-28’,
          orgCode: ‘SK316005’
        }

去url encode为字符串形式:

        body: ‘currTime=2017-07-28&orgCode=SK316005’

js url encode

encodeURI() – JavaScript | MDN

Encode URL in JavaScript? – Stack Overflow

JavaScript encodeURI() 函数

encodeURIComponent() – JavaScript | MDN

js x-www-form-urlencoded

javascript – How do I POST urlencoded form data with $http in AngularJS? – Stack Overflow

javascript – how to post a x-www-form-urlencoded request from react-native – Stack Overflow

iambumblehead/form-urlencoded: Return an object as an `x-www-form-urlencoded` string

How to make a post request with JSON data in application/x-www-form-urlencoded · Issue #263 · github/fetch

关于ajax 中post请求的几种类型以及衍生的几个思考 · Issue #20 · WynterDing/blog

然后已经用网友的自己写函数的方法,实现了基本的效果。

但是继续参考:

fetch documentation

去改为试试:

URLSearchParams – Web APIs | MDN

刚发现不对:

此处的URLSearchParams是,从(我们想要生成的)字符串,转换为这个类

没发从json的dict转换为编码后的值。

【总结】

用:

  //convert json dict to url encoded string
  //eg: currTime=2017-07-28&orgCode=SK316005
  urlEncodeData(formDataDict){
    let encodedData = Object.keys(formDataDict).map((eachKey) => {
      return encodeURIComponent(eachKey) + ‘=’ + encodeURIComponent(formDataDict[eachKey]);
    }).join(‘&’);
    console.log(‘urlEncodeData -> ‘, encodedData);
    return encodedData;
  }
    let bodyData = {
      currTime: ‘2017-07-28’,
      orgCode: ‘SK316005’
    };
    let postBody = this.urlEncodeData(bodyData);
    console.log(‘postBody=’, postBody);
    //currTime=2017-07-28&orgCode=SK316005

即可得到:

然后供后面的fetch去使用了:

// Note:
    // if error: No Access-Control-Allow-Origin header is present on the requested resource
    // solution:
    // disable CORS
    // (1) Chrome: install plugin and MAKESURE enable it to work
    // https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
    // (2) Safari
    // in development mode, Development -> Disable CORS
    fetch(
      ‘http://xxx/getProgressData’,
      {
        method : ‘POST’,
        headers : {
          ‘Content-Type’: ‘application/x-www-form-urlencoded; charset=UTF-8’,
          ‘Accept’: ‘application/json’,
        },
        body: postBody
      }
    )
    .then((resp) => {
      console.log(resp);
      let respJson = resp.json(); //typeof(respJson)= object
      console.log(‘respJson=’, respJson, ‘typeof(respJson)=’, typeof(respJson));
      return respJson;
    })
    .then((respJsonDict) => {
      console.log(‘parsed respJsonDict=’, respJsonDict);
    });

转载请注明:在路上 » 【已解决】JS中如何实现将字典变量去url的encode

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.177 seconds, using 22.15MB memory