How to pass an array as a URL parameter?

前端 未结 5 1722
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 07:04

I would like to pass an array and added to a link on my page as a URL parameter, because later on the server side I need the values from the array. How should I do that?

相关标签:
5条回答
  • 2021-01-17 07:45

    It should not depend on the server side: By the URI standard specification, all parameters must have one name and should have one value. But there can be several parameters with the same name, which is the right way to serialize an array:

    http://server/context?array=aaa&array=bbb&array=ccc&otherparameter=x

    You could do it like this:

    var s="";
    for (var i=0;i< myArray.length;i++)
    {
      s+="&myArray="+myArray[i];
    }
    var url="http://server/context?"+s;
    
    0 讨论(0)
  • 2021-01-17 07:46

    Pass an array of strings as URL parameters:

    const myLink = 'https:/example.com/api'
    const myArray = ['aaa', 'bbb', 'ccc'];
    let apiUrl = `${myLink}/query?`;
    
    myArray.forEach((x) => {
        apiUrl += `&array=${x}`;
    });
    
    console.log(apiUrl);
    // https://example.com/api/query?array="aaa"&array="bbb"&array="ccc"
    
    0 讨论(0)
  • 2021-01-17 07:48

    I'd go with this approach,

    var myArray = ['aaa', 'bbb', 'ccc', ];
    
    var myArrayQry = myArray.map(function(el, idx) {
        return 'myArray[' + idx + ']=' + el;
    }).join('&');
    
    // myArray[0]=aaa&myArray[1]=bbb&myArray[2]=ccc
    

    Then, I retrieve the URL query params as an array on the server side.

    0 讨论(0)
  • 2021-01-17 08:01

    You can serialize the JSON:

    myArray = ['aaa', 'bbb', 'ccc'];
    var arrStr = encodeURIComponent(JSON.stringify(myArray));
    $('#myLink').attr({ href: '/myLink?array=' + arrStr });
    

    If your parsing (on the next page) is done via JavaScript too, you'll conversely use JSON.parse(). In PHP it would be json_decode().

    0 讨论(0)
  • 2021-01-17 08:04

    try this

    $('#myLink').attr({"href" : '/myLink?array=' + myArray.join(',')});
    

    on server: capture and split data.

    0 讨论(0)
提交回复
热议问题