programing

jQuery를 사용하여 현재 URL을 가져오시겠습니까?

goodsources 2022. 9. 11. 20:05
반응형

jQuery를 사용하여 현재 URL을 가져오시겠습니까?

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');

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

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의 빌트인 개체를 사용할 수 있습니다.

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다만, 다른 종류의 Internet Explorer(6,7)에서는, 같은 방법으로 이러한 방법을 서포트하고 있지 않습니다.window.location.href?window.location.replace()지원되지 않음) 때문에 Internet Explorer를 사용하기 위해서는 항상 조건부 코드를 작성하여 다른 방법으로 접근해야 합니다.

따라서 jQuery를 사용할 수 있고 로드된 경우 이러한 문제를 해결하기 위해 다른 항목과 마찬가지로 jQuery(장소)를 사용하는 것이 좋습니다.그러나 JavaScript를 통한 클라이언트 측 위치 위치 리다이렉트(즉, Google Maps API 및 위치 객체 메서드 사용)를 수행할 경우 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();
}
  • protocol ers Web-browers는 WebHosted Applications와 Web Client(Browser) 간의 통신 규칙을 준수하여 Internet Protocol을 사용합니다.(하드웨어 = 80, https(SSL) = 443, ftp = 21 등)

EX: 기본 포트 번호 사용

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
  • (//) 호스트는 인터넷상의 엔드 포인트(리소스가 존재하는 머신)에 붙여진 이름입니다.www.stackoverflow.com - DNS IP Address of an Application (OR) localhost : 8080 - localhost

도메인 이름은 DNS(Domain Name System) 트리의 규칙 및 절차에 따라 등록됩니다.주소 지정을 위해 IP-Address를 사용하여 도메인을 관리하는 사용자의 DNS 서버입니다.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

  • (/) 이 경로는 웹 클라이언트가 액세스하려는 호스트 내의 특정 리소스에 대한 정보를 제공합니다.
  • (?) 옵션쿼리는 딜리미터(&)로 구분된 일련의 Atribute-Value 쌍을 전달합니다.
  • (#) 옵션의 fragment는 특정 요소의 id Atribut인 경우가 많아 웹 브라우저는 이 요소를 뷰로 스크롤합니다.

파라미터에 Epoch가 있는 경우 ?date=1467708674를 사용합니다.

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

URL 여기에 이미지 설명 입력


username, @ 사용자 이름: password URL, usernaem/password가 포함된 경우
들면 다음과 같습니다.

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

그런 다음 URL을 인코딩해야 합니다.

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

encodeURI() (vs) 예

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 (-_.!~*')
*/

window.location에 로그인하여 URL만 사용할 수 있는 모든 옵션을 표시할 수 있습니다.

window.location.origin

전체 경로 사용:

window.location.href

위치도 있어요__

.host
.hostname
.protocol
.pathname

그러면 JavaScript/jQuery를 사용하여 현재 페이지의 절대 URL이 반환됩니다.

  • document.URL

  • $("*").context.baseURI

  • location.href

GET 변수를 제거할 수 있는 방법이 있습니다.

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

모든 브라우저가 Javascript window 객체를 지원합니다.브라우저 창을 정의합니다.

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

모든 글로벌 변수는 창 개체 속성이며 모든 글로벌 함수는 해당 메서드입니다.

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>

URL과 해시 태그를 연결하는 사용자가 있는 경우 다음 두 가지 함수를 결합합니다.

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

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');

다음은 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);
});

iframe 내에서 부모 창의 URL을 가져오려면 다음 절차를 수행합니다.

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

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

다음은 사용할 수 있는 유용한 코드 스니펫의 예입니다.예를 들어 jQuery에 한정되지 않은 표준 JavaScript 함수를 사용하는 예도 있습니다.

URL & Query 문자열에 대해서는 8개의 유용한 jQuery 스니펫을 참조하십시오.

var path = location.pathname재 url URL 로(((((( ( jQuery ) 。「 」의 window.location는 옵션입니다.

window.location현재 URL을 제공하며 원하는 URL을 추출할 수 있습니다.

루트 사이트의 경로를 가져오려면 다음을 사용합니다.

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

window.location.href사용합니다.그러면 전체 URL이 표시됩니다.

purl.js 참조.이는 jQuery에 따라 매우 유용하고 사용할 수도 있습니다.다음과 같이 사용합니다.

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

가장 일반적으로 사용되는 상위 3개는 다음과 같습니다.

1. window.location.hostname 
2. window.location.href
3. window.location.pathname
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

다음 코드로 Jquery의 현재 URL을 얻을 수 있습니다.

$(location).attr('hostname');                //origin URL
$(location).attr('pathname');                // path name
$(location).attr('hash');                    // everything comes after hash
// get current URL

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

언급URL : https://stackoverflow.com/questions/406192/get-current-url-with-jquery

반응형