微博把mid加密了,要转化才能变成id,所以两个之间需要想互转换,js代码如下:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>this is weibo id2mid</title>
  5. </head>
  6. <body>
  7. </body>
  8. <script type="text/javascript">
  9. this.str62keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  10. /**
  11. * 10进制值转换为62进制
  12. * @param {String} int10 10进制值
  13. * @return {String} 62进制值
  14. */
  15. window.fun1 = function int10to62(int10) {
  16. var s62 = '';
  17. var r = 0;
  18. while (int10 != 0) {
  19. r = int10 % 62;
  20. s62 = this.str62keys.charAt(r) + s62;
  21. int10 = Math.floor(int10 / 62);
  22. }
  23. return s62;
  24. }
  25. /**
  26. * 62进制值转换为10进制
  27. * @param {String} str62 62进制值
  28. * @return {String} 10进制值
  29. */
  30. window.fun2 = function str62to10(str62) {
  31. var i10 = 0;
  32. for (var i = 0; i < str62.length; i++) {
  33. var n = str62.length - i - 1;
  34. var s = str62.substr(i, 1); // str62[i]; 字符串用数组方式获取,IE下不支持为“undefined”
  35. i10 += parseInt(this.str62keys.indexOf(s)) * Math.pow(62, n);
  36. }
  37. return i10;
  38. }
  39. /**
  40. * id转换为mid
  41. * @param {String} id 微博id,如 "201110410216293360"
  42. * @return {String} 微博mid,如 "wr4mOFqpbO"
  43. */
  44. window.fun3 = function id2mid(id) {
  45. if (typeof (id) != 'string') {
  46. return false; // id数值较大,必须为字符串!
  47. }
  48. var mid = '';
  49. for (var i = id.length - 7; i > -7; i = i - 7) //从最后往前以7字节为一组读取mid
  50. {
  51. var offset1 = i < 0 ? 0 : i;
  52. var offset2 = i + 7;
  53. var num = id.substring(offset1, offset2);
  54. num = fun1(num);
  55. mid = num + mid;
  56. }
  57. return mid;
  58. }
  59. /**
  60. * mid转换为id
  61. * @param {String} mid 微博mid,如 "wr4mOFqpbO"
  62. * @return {String} 微博id,如 "201110410216293360"
  63. */
  64. window.fun4 = function mid2id(mid) {
  65. var id = '';
  66. for (var i = mid.length - 4; i > -4; i = i - 4) //从最后往前以4字节为一组读取mid字符
  67. {
  68. var offset1 = i < 0 ? 0 : i;
  69. var len = i < 0 ? parseInt(mid.length % 4) : 4;
  70. var str = mid.substr(offset1, len);
  71. str = fun2(str).toString();
  72. if (offset1 > 0) //若不是第一组,则不足7位补0
  73. {
  74. while (str.length < 7) {
  75. str = '0' + str;
  76. }
  77. }
  78. id = str + id;
  79. }
  80. return id;
  81. }
  82. console.log(fun4('H2NHjrBuh'));
  83. </script>
  84. </html>

分类: web

标签:   javascript