Send array with GET Request

19,566

You can't simply pass an array as a query parameter. You will need to iterate over the array and add it so the URL string such as ?array[]=one&array[]=two

Here is a basic jsfiddle as an example

var a=['one', 'two'];
var url = 'www.google.com';

for (var i=0; i<a.length; ++i) {
    if (url.indexOf('?') === -1) {
        url = url + '?array[]=' + a[i];  
    }else {
        url = url + '&array[]=' + a[i];
    }
}

console.log(url);
Share:
19,566
spen123
Author by

spen123

SOreadytohelp

Updated on June 04, 2022

Comments

  • spen123
    spen123 almost 2 years

    I am making a get request form Javascript to Python. And I am trying to pass a 2D array so something like

    [["one", "two"],["foo", "bar"]]
    

    And here is what I am currently trying but it is not working.

    So in my javascript I have an array that look similar to the one above, and then pass it like this

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "http://192.67.64.41/cgi-bin/hi.py?array=" + myArray, false );
    xmlHttp.send( null );
    

    And then in python I get it like this

    import cgi
    form = cgi.FieldStorage()
    array = form.getvalue("array")
    

    But it doesn't come out right, in python then if I were to do

    print array[0]
    #I get -> "o"
    print array[1]
    #I get -> "n"
    print array[2]
    #I get -> "e"
    

    and so on, but if I what I want is

    print array[0]
    #output -> ["one", "two"]
    

    How can I accomplish this?

    Thanks