jQuery variable redirects to undefined url despite it being a string
P粉478188786
P粉478188786 2024-04-01 21:03:17
0
1
490

I'm having trouble trying to redirect to a new URL using jQuery, but somehow it doesn't work in this specific case. I'm using jQuery with html and Django backlog, but I don't think any of these are causing the undefined parameters to be shown. The code is quite simple:

$(document).on('click', '.view-diagnostics', function(){
    let url = $(this).data("href");
    window.location.pathname = url;
})

The clicked html element is as follows:

<td>
    <div class="view-diagnostics">
        <button class="button h-btn view-diagnostics" data-href="{% url "internet:diagnose" %}">{% trans "View diagnostics"%} </button>
    </div>
</td>

In this case, I can use console.log(url) to log the URL and get a string in the form "/something/something/", and I can use browse The inspection tool in the browser uses breakpoints to see that the URL does indeed contain the correct URL, and I can get the type of the URL, which is a string. However, when I click the button that executes this code, the site redirects to http://127.0.0.1:8000/undefined (I'm using a local server), so somehow the URL is now Not defined.

I've tried a lot of different ways to do this, including trying every method of redirecting to a new url, including window.location=url, window.location.href= url, but it always pops up as undefined. I've also tried printing the content and type of the URL and it all looks fine. The weirdest part for me is that if I change the code to

$(document).on('click', '.view-diagnostics', function(){
    let url = $(this).data("href");
    url = "/something/something/"
    window.location.pathname = url;
})

Even if I copy and paste the URL from the console.log() result of the first let URL line, the code correctly redirects to the correct URL.

To summarize the problem: There is a button that contains a URL from the data-href package. When the button is clicked, I get the URL in jQuery and save it as a URL. I can now use console.log() to log the URL and get the type, and then I get the URL and the type I expect (a string). When I try to redirect to this URL I get the error Unable to redirect to URL http://127.0.0.1:8000/undefined. When I hardcoded the URL to a copy-pasted string from an earlier logging test, the redirect suddenly worked. Does anyone know what else I can try to resolve this issue?

P粉478188786
P粉478188786

reply all(1)
P粉448130258

Your selector .view-diagnostics matches two elements. button and div.

Call your function for the button and assign your desired value to window.location.pathname.

The event then bubbles up to the div and calls the function a second time. div does not have any data-* attributes, so url is undefined. It is assigned to window.location.pathname and overwrites the previous assignment.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template