I have a series of links which I want to call using 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. 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');
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.