用jQuery将JavaScript对象转换为querystring查询字符串

栏目: jQuery · 发布时间: 7年前

内容简介:在get方式的参数传递中,常常需要将JavaScript对象,转换成查询字符串,比如:会转换成输出:

在get方式的参数传递中,常常需要将JavaScript对象,转换成查询字符串,比如:

{ method: 'get', state: '200' }

会转换成

?method=get&state=200

方法1:用JavaScript

serialize = function(obj) {
  var str = [];
  for (var p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
}
console.log(serialize({
  foo: "hi there",
  bar: "100%"
}));

输出:

// foo=hi%20there&bar=100%25

方法2: 用jQuery插件

jQuery的$.param内置此方法,可直接使用:

var data = { method: 'get', state: '200' }
var send = $.param(data)

console.log(send)
// method=get&state=200

jQuery 的get方法会默认使用 $.param 转换的参数:

$.get('/test', { a: 1, b: 1}) 
> GET http://ourjs.com/test?a=1&b=1 404 (Not Found)

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

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

Web 2.0 Heroes

Web 2.0 Heroes

Bradley L. Jones / Wiley / 2008-04-14 / USD 24.99

Web 2.0 may be an elusive concept, but one thing is certain: using the Web as merely a means of retrieving and displaying information is history. Today?s Web is immediate, interactive, innovative. It ......一起来看看 《Web 2.0 Heroes》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

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

UNIX 时间戳转换

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

RGB CMYK 互转工具