开发者

How can I get URL parameter in a jquery ready function?

I have the following:

$(document).ready(function() {
window.location.href='http://target.SchoolID/set?text=';
});

So if someone comes to a page with the above mentioned code using a url like:

Somepage.php?id=abc123

I want the text variable in the ready function to read: a开发者_C百科bc123

Any ideas?


you don't need jQuery. you can do this with plain JS

function getParameterByName( name ) //courtesy Artem
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

and then you can just get the querystring value like this:

alert(getParameterByName('text'));

also look here for other ways and plugins: How can I get query string values in JavaScript?


check out the answer to this questions: How can I get query string values in JavaScript?

that'll give you the value of the id parameter from the query string.

then you can just do something like:

$(document).ready(function() {
    var theId = getParameterByName( id)
    var newPath = 'http://target.SchoolID/set?text=' + theId
    window.location.href=newPath;
});


To help people coming after me that want to have multiple variables and to enhance Moin's answer here is the code for multiple variables:

function getParameterByName( name ) //courtesy Artem
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
  {
    if ((results[1].indexOf('?'))>0)
        return decodeURIComponent(results[1].substring(0,results[1].indexOf('?')).replace(/\+/g, " "));
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜