从单击使用属性作为变量进行AJAX调用。
16lz
2021-01-22
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调用来发布。
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);
});
});
1 个解决方案
#1
3
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.
但是,一个标签通常没有一个值属性,所以我建议使用数据属性来保持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);
});
});
更多相关文章
- 确保代码在*之后执行*对监视属性的更改已在UI中生效
- JavaScript 对象属性作实参以及实参对象的callee属性
- JSON.parse(xhr.responseText)意外的字符串错误
- 如何在url中将特殊字符作为查询字符串传递
- JS计算任意字符串宽度
- 如何在JavaScript中按大写和小写分割字符串?
- 使用jackson json将属性添加到json字符串
- ajax请求返回一个空字符串作为响应
- React组件的属性PropTypes