簡體   English   中英

<a href>單擊使用屬性作為變量進行</a> AJAX調用

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

我有一個鏈接

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

我想通過AJAX調用來POST。

這是我的代碼。

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

簡單,只需讀取屬性,使用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);
    });
});

但是, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM