富贵资源网 Design By www.hznty.com

朋友问的一个面试题:有个url,要求获取url 的参数,返回值为json格式。

简单的写了下,发笔记备份。

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>simple a example for url to json</title>
 <script>
 var url = 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=慕课&rsv_pq=e379bd8200001a8c&rsv_t=ea8cxrgm03IFb44zHA261P6KziPRXAekcjwsRJtUSKLUmKweFsZFXE%2BUSrU&rqlang=cn&rsv_enter=0&rs';

 function url2json(url){
  var index = -1,
     str = '',
     arr = [],
     length = 0,
     res = {};
  if(url.indexOf('?')!=-1){
  index = url.indexOf('?');
  str = url.substring(index+1);
  arr = str.split('&');
  length = arr.length;
  for(var i=0; i<length-1; i++){
   res[arr[i].split('=')[0]] = arr[i].split('=')[1];
  }
  }else{
  res = {};
  }
  return res;
 };

 var result = url2json(url);

 //获取json的键值对条数(模拟长度)
 var length = 0;
 for(var i in result){
  length++;
 }


 //在页面输出
 var tL = 0;
 document.write('{<br>');
 for(var name in result){
  tL++;
  
  if(tL == length){
  document.write('&nbsp&nbsp'+name+':'+result[name]+'<br>');
  }else{
  document.write('&nbsp&nbsp'+name+':'+result[name]+',<br>'); 
  }
 }
 document.write('}');
 </script>
</head>
<body>

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com