简体   繁体   中英

Get URL parameters from text link and post to AJAX call

I'm currently working on a bit of jQuery that will allow users to make an AJAX call from a text link. This is no problem but the text link has parameters that I need to send to the AJAX request in order for it to execute properly.

My text link looks something like this:

<a href="?affiliate=one&voteType=two">Click here</a>

Here is my jQuery:

function getUrlParam(name)
{
  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 results[1];
}


/* Let's create a function that will allow us to vote on the hosts */

function hostVote() {

/* These variables are used to determine the button clicked */

    var affiliate = getUrlParam('affiliate');
    var voteType = getUrlParam('voteType');

    $.ajax({
      cache: false,
      type: "POST",
        url: "/php/hostvote.php",
        data: "affilate=" + affiliate + "&voteType=" + voteType +"",
        success: voteSubmitted
    });

    function voteSubmitted() {
        alert('Thanks for voting');
        $(this).addClass('yes');
    }
    return false;   
};

$("a.vote").click(hostVote);

The trouble with this code is I can't submit the link to put any parameters in the url before the function is executed, resulting in empty affiliate and voteType vars.

Can anyone help?

A better approach would be to store the data you need in the data-* attribute of the link. This would make it much easier to retrieve the corresponding data. Here's a simple example of how it would work.

<a href="#" data-affiliate="one" data-voteType="two">Click here</a>

$("a.vote").click(function(e){ 
    var affiliate = $(this).data('affiliate');
    var voteType =  $(this).data('voteType');
    // do your ajax call here 
    e.preventDefault(); 
}); 

Instead of -

var results = regex.exec( window.location.href );

could you do -

var results = regex.exec($("a.vote").attr('href'));

and parse the variables directly from your link?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM