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);
    });
});

更多相关文章

  1. 确保代码在*之后执行*对监视属性的更改已在UI中生效
  2. JavaScript 对象属性作实参以及实参对象的callee属性
  3. JSON.parse(xhr.responseText)意外的字符串错误
  4. 如何在url中将特殊字符作为查询字符串传递
  5. JS计算任意字符串宽度
  6. 如何在JavaScript中按大写和小写分割字符串?
  7. 使用jackson json将属性添加到json字符串
  8. ajax请求返回一个空字符串作为响应
  9. React组件的属性PropTypes

随机推荐

  1. 【Android】Android 概述_问答
  2. 深入解析Android关机
  3. Android分析View的scrollBy()和scrollTo(
  4. Android(安卓)UI 优化 使用和 标签
  5. 【Android语音合成TTS】云知声离线TTS使
  6. Android静默安装和静默卸载
  7. Android实时抓包分析 : 善用adb调试桥
  8. Android事件分发机制详解:史上最全面、最
  9. 【android】使用android-resource-remove
  10. Android(安卓)Map Api 使用和开发(1) 添