[英]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. 我想通过AJAX调用来POST。
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. 简单,只需读取属性,使用
encodeURIComponent
进行编码,并将值连接到字符串中。
$('#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
标签通常没有value
属性,因此我建议使用数据属性来保持HTML的良好和有效。
<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);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.