简体   繁体   中英

Make AJAX call from <a href> click using attribute as a variable

I have a link

<a id="container" value="{$variable}" href="#">Click This</a>

That I would like to use to POST via an AJAX call.

Here is my code.

$('#container').click(function(event){
   event.preventDefault();
   $.post('/cart.php?mode=add&productid={$variablegoes here}&amount=1&redirect_from_cart=Y', function(response){
      alert(response);
   });
});

Easy, just read the attribute, encode with encodeURIComponent , and concatenate the value into the string.

$('#container').click(function(event){
    event.preventDefault();
    var variable = $(this).attr('value');
    $.post('/cart.php?mode=add&productid=' + encodeURIComponent(variable) + '&amount=1&redirect_from_cart=Y', function(response){
        alert(response);
    });
});

The a tag does not normally have a value attribute however, so I would recommend using a data attribute instead to keep the HTML nice and valid.

<a id="container" data-value="{$variable}" href="#">Click This</a>
$('#container').click(function(event){
    event.preventDefault();
    var variable = $(this).attr('data-value');
    $.post('/cart.php?mode=add&productid=' + encodeURIComponent(variable) + '&amount=1&redirect_from_cart=Y', function(response){
        alert(response);
    });
});

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