Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...