[英]Call Ajax on href click
I have a series of links which I want to call using Ajax我有一系列我想使用 Ajax 调用的链接
<a href="AddElement.php?Type=Example">Link</a>
<a href="AddElement.php?Type=ExampleTwo">Link</a>
<a href="AddElement.php?Type=ExampleThree">Link</a>
I have tried the below to no avail:我尝试了以下方法无济于事:
<a id="data" href="#" data-href="Example">
<script type="text/javascript">
$(document).on('click','#data',function(e) {
e.preventDefault();
e.stopPropagation();
var data = $(this).data('href');
$.ajax({
method: 'get',
url: 'AddElement.php?Type=',
data: data,
async: true,
cache: false,
success: function (data){
alert('Success');
}
});
});
</script>
Can anyone help?任何人都可以帮忙吗?
Define custom attributes and use those in the script as below.定义自定义属性并在脚本中使用这些属性,如下所示。
data-url="AddElement.php?Type=" href="#" data-value="Example"
$(document).on('click','#data',function(e) { e.preventDefault(); e.stopPropagation(); var URL = $(this).data('url'); var data = $(this).data('value'); $.ajax({ method: 'get', url: URL, data: data, async: true, cache: false, success: function (data){ alert('Success'); }, error: function (data) { console.log('Error'); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <aa id="data" data-url="AddElement.php?Type=" href="#" data-value="Example">Text</a>
You need to use the data-href
value in the url
option, not in the data
option.您需要在
url
选项中使用data-href
值,而不是在data
选项中。 Therefore it should be因此应该是
var hrefVal = $(this).data('href');
$.ajax({
method: 'get',
url: 'AddElement.php?Type=' + hrefVal,
async: true,
cache: false,
success: function (data){
alert('Success');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.