I'm trying to GET some data from a site using jQuery $.get. I need to set 2 parameters of the same type:
..&q=Some Text&q=Some other text
jQuery appears to be overwriting the first instance of q with the second and only sending 1. Any way around this?
This is the code I was trying to use:
var params = {
"otherParam":"x",
"q":text,
"q":title
};
$.get(url, params, mySuccessFunction);
The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".
Try:
var params = {
"otherParam": "x",
"q": [ text, title ]
};
edit — more information: array-valued parameters like that are treated specially by jQuery. To appease many common server frameworks, by default (since release 1.5 or 1.6 I think) those will result in parameter names that include "[]" (open- and close-bracket characters) as a suffix (no number, contrary to my erroneous comment below). If you don't want that, you can set
jQuery.ajaxSettings.traditional = true;
and it'll just be "q" instead of "q[]".
And another way to solve it that does not require encodeURIComponent()
or messing with jQuery.ajaxSettings.traditional = true;
which I would prefer not to do because I don't want to interfere (even temporarily) with what other parts of the site might be doing simultaneously.
Is:
var params=[
{name:"q", value:title},
{name:"q", value:text}
];
$.get(url, params, mySuccessFunction);
Another approach without modifying jQuery.ajaxSettings.traditional = true;
is to use $.param()
http://api.jquery.com/jQuery.param/
So something like this:
var params = {
"otherParam": "x",
"q": [ text, title ]
};
$.get(url, $.param(params, true), mySuccessFunction);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With