Get current URL with jQuery?

后端 未结 30 2266
你的背包
你的背包 2020-11-22 02:44

I am using jQuery. How do I get the path of the current URL and assign it to a variable?

Example URL:

http://localhost/menuname.de?foo=bar&nu         


        
相关标签:
30条回答
  • 2020-11-22 03:28

    You can log window.location and see all the options, for just the URL use:

    window.location.origin
    

    for the whole path use:

    window.location.href
    

    there's also location.__

    .host
    .hostname
    .protocol
    .pathname
    
    0 讨论(0)
  • 2020-11-22 03:29

    window.location is an object in javascript. it returns following data

    window.location.host          #returns host
    window.location.hostname      #returns hostname
    window.location.path          #return path
    window.location.href          #returns full current url
    window.location.port          #returns the port
    window.location.protocol      #returns the protocol
    

    in jquery you can use

    $(location).attr('host');        #returns host
    $(location).attr('hostname');    #returns hostname
    $(location).attr('path');        #returns path
    $(location).attr('href');        #returns href
    $(location).attr('port');        #returns port
    $(location).attr('protocol');    #returns protocol
    
    0 讨论(0)
  • 2020-11-22 03:29

    Very Commonly Used top 3 ones are

    1. window.location.hostname 
    2. window.location.href
    3. window.location.pathname
    
    0 讨论(0)
  • 2020-11-22 03:30

    In pure jQuery style:

    $(location).attr('href');
    

    The location object also has other properties, like host, hash, protocol, and pathname.

    0 讨论(0)
  • 2020-11-22 03:30

    If there is someone who wants to concatenate the URL and hash tag, combine two functions:

    var pathname = window.location.pathname + document.location.hash;
    
    0 讨论(0)
  • 2020-11-22 03:31

    Here is an example to get the current URL using jQuery and JavaScript:

    $(document).ready(function() {
    
        //jQuery
        $(location).attr('href');
    
        //Pure JavaScript
        var pathname = window.location.pathname;
    
        // To show it in an alert window
        alert(window.location);
    });
    
    
    $.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){
        //alert(json.message);
    });
    
    0 讨论(0)
提交回复
热议问题