0

Sorry I'm new in Javascript. I wanna get a number from my url in javascript, because I need it very much. I'd got this code from another link but it's not perfect enough for my case. The code is like this:

<html>
<head>
    <style>
    </style>
    <script type="text/javascript">
        function kampret(){
            x=location.pathname.split('/')[1];
            alert(x);
        }
    </script>
</head>
<body onload='kampret()'>
</body>
</html>

My url is like this:

http://domain.com/ztest1.php?ai=85&ver=7

I want to get that number of '85', and i used that code and the result is ztest1.php not 85. And how do i get the only 85? Thank you.

Juna serbaserbi
  • 205
  • 2
  • 12
  • 9
    Possible duplicate of [How to get the value from the URL parameter?](http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-url-parameter) – Alex Andrei Nov 11 '15 at 08:32

4 Answers4

5

You can try

var getUrlParams = function (url) 
{
  var params = {};
  (url + '?').split('?')[1].split('&').forEach(
    function (pair) 
    {
       pair = (pair + '=').split('=').map(decodeURIComponent);
       if (pair[0].length) 
       {
         params[pair[0]] = pair[1];
       }
  });

  return params;
};

Result is

Object {ai: "85", ver: "7"}

Usage:

// 'http://domain.com/ztest1.php?ai=85&ver=7'
var params = getUrlParams( window.location.href );
alert( params.ai ); // 85
mischaZeng
  • 166
  • 6
2

Try with this:

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}

$(document).ready(function(){
    alert(getURLParameter('ai'));
}); //JQuery

window.onload = alert(getURLParameter('ai')); //JavaScript

Adopted for yours:

<body onload='kampret()'></body>
<script>
    function getURLParameter(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
    }

    function kampret() {
        alert(getURLParameter('ai'));
    }
</script>
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
1

Try with this:

//var url = "http://domain.com/ztest1.php?ai=85&ver=7";
var url = window.location.href;
var idx = url.indexOf("?");
var idx2 = url.indexOf("&");
var hash = idx != -1 ? url.substring(idx+4, idx2) : "";

And if you want only the 85 in this code you can use hash = idx != -1 ? hash.substring(3, idx) : "";

piterio
  • 760
  • 1
  • 6
  • 23
1

A smaller way using php and javascript.

<?php $id = $_GET['ai']; ?>
<script language="javascript">
var id = <?php echo $id; ?>;
alert(id);
</script>
Ali Zia
  • 3,825
  • 5
  • 29
  • 77