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
1.1k views
in Technique[技术] by (71.8m points)

ajax - JQuery removes empty arrays when sending

I have the following code:

$.post('block_ajax.php'
    ,   {   'action': 'set_layout'
        ,   'listid': 123
        ,   'layout': []
        }
    ,   function(data) {
            // ...
        }
);

The recieving script (block_ajax.php) only recieves the "action" and "listid" parameters. When I inspect what is sent using Chrome, I see the "layout" parameter isn't even send to the backend script.

Since there is a difference between an empty array and the absence of an array, I'd like to have JQuery send the empty array. I can find some indications that JQuery (1.6.1) seems to do this, but not how to stop it from doing so. JSON format allows for empty arrays and empty objects, so I think it should be possible.

Does anybody know what to change so JQuery can send empty arrays?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Our organization has two approaches to the problem:

  • Sending data as JSON as opposed to POST-data is a good all-purpose approach, though this is sometimes a little bit difficult to integrate with frameworks like Rails, because you may have to add explicit back-end calls to decode the JSON data.
  • [""] as noted by vinod will work well, as many frameworks (e.g. Rails) will often treat this as an empty array. (for the reason, see this Stack Overflow answer).
    • Note: This works when trying to integrate with some aspects of Rails, specifically when sending a list of ids of objects that are related by a has_many relationship. E.g. if you have a foos table and a bars table, and foos has_many :bars through :foo_bars, a way to remove all associations on a foo object is to pass foo: { bar_ids: [""] }.

Both approaches are hackier than desired, and I would be glad to discover a cleaner approach.


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

...