开发者

append url with a session id jquery

I have a static session ID i'm using and need to add it to a url when clicked, but can't seem to get it right. If you go to http://www.mysite.com/test.php you get redirected, the session id XYX needs to be added, so the correct url to hit the page would be http://www.mysite.com/test.php?sessionid=XYX

<a href="http://www.mysite.com/test.php" class="foo">link here</a>

$('.foo').click(function(){
  (this).append(?sessionid=XYX');'
});

I know this is wrong, al开发者_运维技巧l documentation Ive found is much more complex than my needs. thanks!


This should add the session ID and send the user to the new url, use the e.preventDefault to stop the system using the normal event, then add the session id to the url and send the browser there:

<a href="http://www.mysite.com/test.php" class="foo">link here</a>

$('.foo').click(function(e)
{
    e.preventDefault();
    window.location = $(this).attr('href') + '?sessionid=XYX';
});


You'll want to change the href attribute, like this:

$('.foo').click(function(){
  $(this).attr('href', $(this).attr('href') + '?sessionid=XYX');
});

I was actually skeptical of this for a moment - I wasn't sure if the change to the URL was going to affect the destination of the link, but it does. The change happens and then after it's done, the default action fires, loading the modified link. Here's a demo: http://jsfiddle.net/Mgv34/


Give this a shot.

$('.foo').click(function(){
  if( !this.search ) this.search = '?sessionid=XYX';
});

The search property lets you set the query string directly on the element.


Changing hrefs with onClick is dangerous without checking if the href contains '?sessionid=XYX', because next clicks to the link gives you "http://www.example.com/test.php?sessionid=XYX?sessionid=XYX"

I suggest

$('.foo').click(function(){
  var lHref = $(this).attr('href');
  var lStr = '?sessionid=XYX';
  if (lHref.indexOf(lStr) < 0) { 
    $(this).attr('href', lHref + lStr);
  }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜