How do I redirect and send url get value to another page using Javascript?

Asked

Viewed 182 times

0

I’m picking up an URL item with this code :

function GetQueryString(a)
{
    a = a || window.location.search.substr(1).split('&').concat(window.location.hash.substr(1).split("&"));

    if (typeof a === "string")
        a = a.split("#").join("&").split("&");


    if (!a) return {};

    var b = {};
    for (var i = 0; i < a.length; ++i)
    {

        var p = a[i].split('=');

        if (p.length != 2) continue;

        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }

    return b;
}


var qs = GetQueryString();

  qs["item"]; // Item que eu estou pegando da url ex: 
     https://meusite.com/pagina.php?item=(valor que eu quero pegar)

And after you effect this process, I would like that with the value obtained from

variable "Qs" concatenate with the link of the new page that would be redirected after 3 seconds, I am using this code:

setTimeout("document.location = 'https://www.meusite.com/pagina.php?item='" + `qs['item']`,3000);

How can I fix this code ?

1 answer

1


The function does not return an array. Alias, you are referencing a key, as if it were an associative array. This does not exist in Javascript.

Return is an object JSON and should be accessed this way: qs.item. The correct code (I put an Alert to show the URL) to redirect is as follows:

function GetQueryString(a)
{
    a = a || window.location.search.substr(1).split('&').concat(window.location.hash.substr(1).split("&"));

    if (typeof a === "string")
        a = a.split("#").join("&").split("&");


    if (!a) return {};

    var b = {};
    for (var i = 0; i < a.length; ++i)
    {

        var p = a[i].split('=');

        if (p.length != 2) continue;

        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }

    return b;
}


var qs = GetQueryString();

URL = "https://meusite.com/pagina.php?item=" + qs.item;

alert(URL);

window.location = URL;
  • Thanks so much @mauhumor, one more question if you could help me, as I could for that qs.item within an html attribute such as the attribute I am using is data-channel-external-id="(valor da url aqui dentro)"

  • You can use the "setAttribute" method documented here: http://www.w3schools.com/jsref/met_element_setattribute.asp

  • 'Cause I was trying this one before but it wasn’t working out here, I was doing the following, I did this job function urlid() {&#xA; document.getElementsByTagName("BUTTON")[0].setAttribute("data-channel-external-id", "qs.item"); } and the attribute inside the HTML data-channel-external-id="urlid()" but I couldn’t, which you think I might be doing wrong?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.