문제

나는 jQuery를 사용하고 있습니다. 현재 URL의 경로를 가져 와서 변수에 할당하려면 어떻게해야합니까?

예제 URL :

http://localhost/menuname.de?foo=bar&number=0
도움이 되었습니까?

해결책

경로를 얻으려면 다음을 사용할 수 있습니다.

var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)

다른 팁

순수한 jQuery 스타일로 :

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

위치 개체에는 호스트, 해시, 프로토콜 및 PathName과 같은 다른 속성도 있습니다.

http://www.refulz.com:8082/index.php#tab2?foo=789

Property    Result
------------------------------------------
host        www.refulz.com:8082
hostname    www.refulz.com
port        8082
protocol    http:
pathname    index.php
href        http://www.refulz.com:8082/index.php#tab2
hash        #tab2
search      ?foo=789

var x = $(location).attr('<property>');

jQuery가있는 경우에만 작동합니다. 예를 들어:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php
</script>
</html>

URL에있는 해시 매개 변수가 필요한 경우 window.location.href 더 나은 선택 일 수 있습니다.

window.location.pathname
=> /search

window.location.href 
 => www.website.com/search#race_type=1

JavaScript의 내장을 사용하고 싶을 것입니다 window.location 물체.

이 기능을 JavaScript로 추가하면 현재 경로의 절대 경로를 반환합니다.

function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}

나는 그것이 당신에게 효과가 있기를 바랍니다.

Window.location은 JavaScript의 객체입니다. 다음 데이터를 반환합니다

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

jQuery에서 사용할 수 있습니다

$(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

이것은 많은 사람들이 생각하는 것보다 더 복잡한 문제입니다. 여러 브라우저가 내장 JavaScript 위치 개체 및 관련 매개 변수/메소드를 통해 window.location 또는 document.location. 그러나 인터넷 익스플로러의 다른 맛 (6,7)은 같은 방식으로 이러한 방법을 지원하지 않습니다.window.location.href? window.location.replace() 지원되지 않음) 따라서 인터넷 익스플로러에게 항상 조건부 코드를 작성하여 다르게 액세스해야합니다.

따라서 jQuery를 사용할 수 있고로드 한 경우 다른 문제를 해결하기 때문에 언급 한 것처럼 jQuery (위치)를 사용할 수도 있습니다. 그러나 JavaScript (즉, Google Maps API 및 Location Object Method를 사용하여)를 통한 예제의 클라이언트 측 지질 위치 리디렉션을 수행하면 전체 jQuery 라이브러리를로드하고 조건부 코드를 작성하지 않으려는 경우 Internet Explorer/Firefox 등의 모든 버전을 확인합니다.

Internet Explorer는 프론트 엔드 코딩 고양이를 불행하게 만듭니다. 그러나 jQuery는 우유 한 접시입니다.

호스트 이름 만 사용하면 사용하십시오.

window.location.hostname

이것은 또한 작동합니다 :

var currentURL = window.location.href;

Java-Script는 브라우저 주소 표시 줄에 표시되는 현재 URL을 검색하는 많은 방법을 제공합니다.

테스트 URL :

http://
stackoverflow.com/questions/5515310/get-current-url-with-jquery/32942762
?
rq=1&page=2&tab=active&answertab=votes
#
32942762
resourceAddress.hash();
console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);

기능:

var webAddress = {};
var param_values = {};
var protocol = '';
var resourceAddress = {

    fullAddress : function () {
        var addressBar = window.location.href;
        if ( addressBar != '' && addressBar != 'undefined') {
            webAddress[ 'href' ] = addressBar;
        }
    },
    protocol_identifier : function () { resourceAddress.fullAddress();

        protocol = window.location.protocol.replace(':', '');
        if ( protocol != '' && protocol != 'undefined') {
            webAddress[ 'protocol' ] = protocol;
        }
    },
    domain : function () {      resourceAddress.protocol_identifier();

        var domain = window.location.hostname;
        if ( domain != '' && domain != 'undefined' && typeOfVar(domain) === 'string') {
            webAddress[ 'domain' ] = domain;
            var port = window.location.port;
            if ( (port == '' || port == 'undefined') && typeOfVar(port) === 'string') {
                if(protocol == 'http') port = '80';
                if(protocol == 'https') port = '443';           
            }
            webAddress[ 'port' ] = port;
        }
    },
    pathname : function () {        resourceAddress.domain();

        var resourcePath = window.location.pathname;
        if ( resourcePath != '' && resourcePath != 'undefined') {
            webAddress[ 'resourcePath' ] = resourcePath;
        }
    },
    params : function () {      resourceAddress.pathname();

        var v_args = location.search.substring(1).split("&");

        if ( v_args != '' && v_args != 'undefined')
        for (var i = 0; i < v_args.length; i++) {
            var pair = v_args[i].split("=");

            if ( typeOfVar( pair ) === 'array' ) {
                param_values[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
            }
        }
        webAddress[ 'params' ] = param_values;
    },
    hash : function () {        resourceAddress.params();

        var fragment = window.location.hash.substring(1);
        if ( fragment != '' && fragment != 'undefined')
            webAddress[ 'hash' ] = fragment;        
    }
};
function typeOfVar (obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
  • 규약 " 웹 브라우저 WebHosted Applications와 Web Client (Browser) 간의 커뮤니케이션 규칙에 따라 인터넷 프로토콜을 사용하십시오. (http = 80, https (ssl) = 443, ftp = 21 등)

예 : 기본 포트 번호가 있습니다

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
  • (//)«호스트는 인터넷의 엔드 포인트 (자원이 살고있는 기계)에 주어진 이름입니다. www.stackoverflow.com- DNS 응용 프로그램의 IP 주소 (OR) LocalHost : 8080 -LocalHost

도메인 이름은 도메인 이름 시스템 (DNS) 트리의 규칙 및 절차에 의해 등록 된 것입니다. DNS 서버는 도메인을 IP-Address로 관리하는 사람의 서버를 해결하기 위해 해결합니다. DNS 서버 계층에서 stackoverlfow.com의 루트 이름은 com입니다.

gTLDs      - com « stackoverflow (OR) in « co « google

로컬 시스템 호스트 파일에서 공개되지 않은 도메인을 유지해야합니다.localhost.yash.com « localhsot - subdomain(web-server), yash.com - maindomain(Proxy-Server). myLocalApplication.com 172.89.23.777

  • (/)«경로는 웹 클라이언트가 액세스하려는 호스트 내의 특정 리소스에 대한 정보를 제공합니다.
  • (?)«선택적 쿼리는 구분 기 (&)로 분리 된 일련의 속성 - 값 쌍을 전달하는 것입니다.
  • (#)«선택적 조각은 종종 특정 요소의 ID 속성이며 웹 브라우저는이 요소를 보았습니다.

매개 변수가있는 경우 시대 ?date=1467708674 그런 다음 사용하십시오.

var epochDate = 1467708674; var date = new Date( epochDate );

URL enter image description here


Usernaem/Password가 @ symbl에 포함 된 경우 사용자 이름 : 비밀번호로 인증 URL
처럼:

Username = `my_email@gmail`
Password = `Yash@777`

그런 다음 URL 인코딩이 필요합니다 @ ~처럼 %40. 나타내다...

http://my_email%40gmail.com:Yash%40777@www.my_site.com

encodeURI() (vs) encodeURIComponent() 예시

var testURL = "http:my_email@gmail:Yash777@//stackoverflow.com?tab=active&page=1#32942762";

var Uri = "/:@?&=,#", UriComponent = "$;+", Unescaped = "(-_.!~*')"; // Fixed
var encodeURI_Str = encodeURI(Uri) +' '+ encodeURI( UriComponent ) +' '+ encodeURI(Unescaped);
var encodeURIComponent_Str =  encodeURIComponent( Uri ) +' '+ encodeURIComponent( UriComponent ) +' '+ encodeURIComponent( Unescaped );
console.log(encodeURI_Str, '\n', encodeURIComponent_Str);
/*
 /:@?&=,# +$; (-_.!~*') 
 %2F%3A%40%3F%26%3D%2C%23 %2B%24%3B (-_.!~*')
*/

URL 사용 만 사용하기 위해 Window.location을 기록하고 모든 옵션을 볼 수 있습니다.

window.location.origin

전체 경로 사용을 위해 :

window.location.href

위치도 있습니다.__

.host
.hostname
.protocol
.pathname

이것은 절대를 반환합니다 URL JavaScript/를 사용한 현재 페이지의jQuery.

  • document.URL

  • $("*").context.baseURI

  • location.href

연결하려는 사람이 있다면 URL 해시 태그, 두 가지 기능을 결합합니다.

var pathname = window.location.pathname + document.location.hash;

Get 변수를 제거 할 수 있습니다.

var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;

JS 자체를 사용하여 길을 얻을 수 있습니다. window.location 또는 location 현재 URL의 객체를 제공합니다

console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);

 var currenturl = jQuery(location).attr('href');

Iframe 내에서 부모 창의 URL을 얻으려면 :

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

NB : 동일한 도메인에서만 작동합니다

다음은 jQuery 및 JavaScript를 사용하여 현재 URL을 가져 오는 예입니다.

$(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);
});

다음은 사용할 수있는 유용한 코드 스 니펫의 예입니다. 일부 예제는 표준 JavaScript 함수를 사용하고 jQuery에만 국한되지 않습니다.

보다 8 개의 유용한 jQuery 스 니펫 및 URL 및 QueryStrings.

사용 Window.location.href. 이것은 당신에게 완전한 것을 줄 것입니다 URL.

Window.location 당신에게 현재를 줄 것입니다 URL, 그리고 당신은 그것에서 원하는 것을 추출 할 수 있습니다 ...

루트 사이트의 경로를 얻으려면 다음을 사용하십시오.

$(location).attr('href').replace($(location).attr('pathname'),'');

보다 Purl.js. 이것은 jQuery에 따라 실제로 도움이되고 사용할 수 있습니다. 다음과 같이 사용하십시오.

$.url().param("yourparam");

var path = location.pathname 현재 URL의 경로를 반환합니다 (JQuery가 필요하지 않음). 사용 window.location 선택 사항입니다.

매우 일반적으로 사용되는 상위 3 개는입니다

1. window.location.hostname 
2. window.location.href
3. window.location.pathname

모든 브라우저는 JavaScript Window 객체를 지원합니다. 브라우저의 창을 정의합니다.

전역 객체와 함수는 자동으로 창 객체의 일부가됩니다.

모든 글로벌 변수는 Window Objects 속성이며 모든 글로벌 기능은 그 방법입니다.

전체 HTML 문서도 창 속성입니다.

따라서 Window.location 객체를 사용하여 모든 URL 관련 속성을 얻을 수 있습니다.

자바 스크립트

console.log(window.location.host);     //returns host
console.log(window.location.hostname);    //returns hostname
console.log(window.location.pathname);         //return path
console.log(window.location.href);       //returns full current url
console.log(window.location.port);         //returns the port
console.log(window.location.protocol)     //returns the protocol

jQuery

console.log("host = "+$(location).attr('host'));
console.log("hostname = "+$(location).attr('hostname'));
console.log("pathname = "+$(location).attr('pathname')); 
console.log("href = "+$(location).attr('href'));   
console.log("port = "+$(location).attr('port'));   
console.log("protocol = "+$(location).attr('protocol'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
// get current URL

$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);

JSTL에서는 현재 URL 경로에 액세스 할 수 있습니다 pageContext.request.contextPath, Ajax 전화를하고 싶다면

  url = "${pageContext.request.contextPath}" + "/controller/path"

예 : 페이지에서 http://stackoverflow.com/questions/406192 이것은 줄 것입니다 http://stackoverflow.com/controller/path

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top