I do front-end dev only like 10% of the time and am curious which is the better way to handle making ajax calls. These calls are just posting data to a web app that specifies an action name and an id.
<a href='javascript:addToList({'action':'set-default-time-zone','id':23})'>set default timezone</a>
<div class='add-to-list action-set-default-time-zone id-23'>set default timezone</div>
I have used both over the years but am not sure which one is preferred. It seems like they get to the same point in the end. Would you consider these to be the two best alternatives and is one better than the other?
I’ve implemented the div method as follows:
$(document).ready(function(){
$('.add-to-list').click(function(){
var id=getId($(this).attr("class"));
var action=getAction($(this).attr("class"));
$.post('/api/' + action,function(data){
...
},'json')
});
});
function getAction(str){
var parts=str.split(' ');
var phrase='action-';
for(i=0; i<parts.length; i++){
var val=parts[i].match(phrase);
if(val!=null){
var action=parts[i].split('action-');
return action[1];
}
}
}
function getId(piece){
var parts=piece.split('id-');
var frag_id=parts[parts.length-1];
var part_id=frag_id.split('-');
var id=part_id[part_id.length-1];
return id;
}
The link method would seem straightforward.
thx
Well the second approach is what you would call Unobtrusive JavaScript. It is believed to be a more robust approach (I’ll avoid the term better here.)
However, your implementation is a bit over-complicated. It could be tuned down to:
HTML:
JavaScript:
The HTML5 specification allows for attributes starting with
data-to be carrying user-defined data. And it’s also backward compatible (will work with older browsers.)