简体   繁体   中英

JQuery array of objects in ajax

I want an array of objects to be sent via post through ajax. Background story: a user selects a number of rooms, and those rooms should be booked in another file using php.
The array/objects is defined as:

var rooms = {};
rooms[rname] = 
                {
                        "rname": rname, // eg 1.27
                        "date": date, // eg 2013-04-24
                        "time": time, // eg 20:15
                        "duration": duration // eg 4
                }

And the ajax call is made

$.ajax({ 
         type: 'GET', //used get to see the parameters passed
         url: 'book_room.php',
         data: rooms
});

However, it seems that the request sent is somewhat like this:

http://url.dk/book_room.php?1.29%5Brname%5D=1.29&1.29%5Bdate%5D=2013-04-28&1.29%5Btime%5D=20%3A15&1.29%5Bduration%5D=4&2.25%5Brname%5D=2.25&2.25%5Bdate%5D=2013-04-28&2.25%5Btime%5D=20%3A15&2.25%5Bduration%5D=4

How can I successfully pass a set of rooms in a request so I can work with them properly? I have a feeling that I have misunderstood the purpose of something here.

Accorting to the API http://api.jquery.com/jQuery.ajax/ You should POST like:

$.ajax({
    contentType:"application/json",
    url:yourEndPoint,
    data:JSON.stringify(yourStuffGoesHere),
    dataType:"json",
    processData:false,
});

As adviced I will post the fix for the problem as an answer.
I Found a solution where X requests are made based on how many rooms were chosen, and it works just fine.

$.each(rooms, function(k,v) {
                    $.ajax({
                        type: 'GET',
                        url: 'book_room.php',
                        data: v
                    });
                });

The requests made this time looks easy to work with. Example requests:

http://url.dk/book_room.php?rname=1.47&date=2013-04-28&time=21%3A00&duration=4 http://url.dk/book_room.php?rname=22.3&date=2013-04-28&time=21%3A00&duration=4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM