Redeem querystring value by jquery load

Asked

Viewed 113 times

0

I’m trying to call a page through the load, this page will have a querystring that I want to pick it up on the call page, but the value comes as null when I try through the load, outside it calling the page alone, everything is ok.

There are 2 pages, 1 main and 2 that will bring an Alert according to the value passed by the query

Main Page (index.html)

<div id="content">resultado</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function carrega(v) {
    $("#content").load("/query/video.html?v="+ encodeURIComponent(v), function(response, status, xhr) {
        if (status == "error") {
            //alert("ocorreu um erro")
        } else {
            //alert("ok")
        }
    });
}

carrega("social");
</script>

Second page (video.html)

<script>
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var foo = getParameterByName('v');
alert(foo);
</script>

If you do the test called already the second page with the query so /video.html? v=teste123 an "teste123" Lert will appear, but when I try to do this through the main page by passing the query parameter and bringing the result by load, simply from the error and the value comes as null.

Could someone explain to me where I’m going wrong?

1 answer

0

Your code is correct, the problem occurs where javascript runs. As you make an Ajax call and play the content in "#content", the javascript runs on the same page you are, ie "window.location.href" is the home page (index.html). You can do a test by adding "v=test" when loading the main page.

Browser other questions tagged

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