How to send an array using jQuery and .ajax method without escaping brackets?

I am trying to send the same parameter name with multiple values, but even after reading the messages in SO I can’t figure out how to do this ... I want to have an destination_input array:

 var myObject = { search_zip: params.search_zip, search_distance: params.search_distance, filter_opts: params.filter_opts, page: params.page, destination_input: ['323 w concord pl #8, chicago, il', '11 e hubbard, chicago, il'] }; 

but this creates a query string:

 search_zip=60614&search_distance=1&filter_opts=discount_check%2Cneed_device_check%2Cauto_track_check&destination_input%5B%5D=323+w+concord+pl+%238%2C+chicago%2C+il&destination_input%5B%5D=11+e+hubbard%2C+chicago%2C+il 

As you can see, it continues to add %5B%5D to destination_input , e.g. &destination_input%5B%5D=11+e+hubbard%2C+chicago%2C+il

This means that everything is messed up on the backend. Any ideas?

+4
source share
3 answers

I assume that your backend is not PHP, as PHP expects [] to indicate that the GET parameter is multi-valued. This means that your backend will process multiple GET arguments with the same key as the array elements, right?

Based on this assumption, you just need to tell jQuery not to automatically add [] when it turns the array into a string of the GET argument.

To do this, you need to pass the argument 'traditional': true as an option to the jQuery ajax function.

Search for “traditional” here: http://api.jquery.com/jQuery.ajax/

+10
source

%5B and %5D are values ​​encoded by the URL [ and ] respectively. They should be part of your input.

In your PHP, execute urldecode(inputString) to decode the values.

0
source

You are currently using the HTTP GET AJAX request to send your data. HTTP POST instead looks more appropriate for your needs.

You not only throw an object into your service, but with an object of such complexity, you can quickly find the exhaustion of characters if you embed your data in the query string.

0
source

Source: https://habr.com/ru/post/1391953/


All Articles