'jQuery get context Root similar to '${pageContext.request.contextPath}' in $.get() method

Here is my jQuery code which works fine

 $("#region").change(function(){
           var region = $("#region").val();
          $.get("../getStates",{ "region":region},function( data ) { 
                var state = $("#state");
                state.find('option').remove();
                state.append($('<option/>').val("").text("----Select"));
                var branch = $("#branch");
                branch.find('option').remove();
                branch.append($('<option/>').val("").text("----Select"));
                if(data == ""){
                    return false;
                }
                var opts = data.split(',');
                $.each(opts, function(i, opt){
                    state.append(
                                $('<option/>').val(jQuery.trim(opt)).text(jQuery.trim(opt)));
                });  
          });
      });

Now if we inspect the $.get() method. I have used ../getStates url to get data from server.

However i want to do the same something like this by getting the context path

${pageContext.request.contextPath}/getStates

the way we do it in jsp. How can this be done. This will help me managing the files if their number increases in future.



Solution 1:[1]

I think you're looking for location.href (https://developer.mozilla.org/en-US/docs/Web/API/Location). It will give you the full URL, and you can chop off the final component.

I don't understand how this is easier to manage than just using the ../ though.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1