开发者

JQuery parameter serialization without the bracket mess

I'm using JQuery to make a JSON request back to the server and it seems that it's parameter serialization is hard-coded开发者_StackOverflow社区 to what PHP expects instead of being generic in nature. Basically I have an object that looks like this:

{
    foo: 1,
    bar : [1, 3, 5]
}

And it serializes it to:

foo=1&bar[]=1&bar[]=3&bar[]=5

Is there anyway to make it just do?

foo=1&bar=1&bar=3&bar=5

It seems to me that jQuery shouldn't be so tied to what a handful of server side frameworks expect as a naming convention. If I wanted my param to be called bar[] I could easily name it that myself if it's what my server-side code expects.


I'm assuming you're using JQuery 1.4. You should take a look at this: http://benalman.com/news/2009/12/jquery-14-param-demystified/

The author discusses why they made JQuery behave this way, and makes some excellent points. For example, if you don't use the "square bracket syntax", you can't pass in arrays with only a single value.

He also offers a work-around:

$.ajaxSetup({ traditional: true });

This will tell JQuery to use the non-bracket method of serialization.


The object can be converted to a parametrized string using $.param(obj,true). The second boolean parameter indicates the traditional method of serializing an object should be used. The traditional method does not use square brackets when it encounters the same parameter name. The serialized string returned from $.param can be passed via any ajax method.

This method is preferred over using $.ajaxSetup() as noted by the jQuery Documentation that states:

Note: The settings specified here will affect all calls to $.ajax or AJAX-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.

Example:

var obj = {myProp: "test", arr: [1,2,3,4]};
var serializedObj = $.param(obj, true); //myprop=test&arr=1&arr=2&arr=3&arr=4

$.post(url,serializedObj,function(){});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜