Home > Blockchain >  Javascript Relative Url Doesn't include Id
Javascript Relative Url Doesn't include Id

Time:09-22

When I make an ajax request using JQuery, the relative url doesn't include the last part of the url. I have the following urls:

/Question/100
/Question/100/AddComment

I am trying to send an ajax request from the first page to the second page. The jquery I am using is:

$.ajax({
    url: 'AddComment',
    type: 'POST'
 });

This ajax request goes to the url

/Question/AddComment

To fix the issue I can just do window.location.href "/AddComment" However I was wondering why exactly does the relative url not include the Id value? Also is there a way to solve this issue without using window.location.href?

CodePudding user response:

This has nothing to do with JavaScript or jQuery, it's just how browsers interpret relative URLs. And for good reason.

The browser doesn't know or care what the "Id" is in the URL. It just knows that you are requesting a resource (100) at the end of a path (/Question/). Any URL relative to that resource is going to be requested relative to that same path. So requesting only AddComment will result in the browser looking for AddComment in the /Question/ path.

Consider what would happen if this wasn't the case. What if you're on the page index.html and you click on a link to about.html. Would you expect or want the browser to navigate to /index.html/about.html? Of course not.

You just need to specify the correct URL. If you can write the full absolute path, great. If you can dynamically output it from server-side code (like the @Url.Route helper in ASP.NET MVC, for example), also great. If you can dynamically build it in JavaScript either based on known base values or from examining the current URL, that's likely just as good as long as you cover any edge cases you might encounter and whatnot. But ultimately you need to specify the URL.

  • Related