Refactoring Jquery: parsing json
I use the following code for two links: a.vote-down-0 and a.vote-up-0, they do the same thing, except each one specifies whether the vote is up or down.
$('a.vote-down-0').click(function() {
var id = $(this).siblings('.reply-id').val();
var ajax_auth_token = $('#auth_token').val();
var c_button = this;
$.post('user/?action=ajax', {
vote_type: 'down',
reply_id: id,
auth_token: ajax_auth_token
}, function(data, return_status) { //return status is just if ajax works or not
var json_data = jQuery.parseJSON(data);
switch(json_data.r_messa开发者_JS百科ge)
{
case "success":
output = "Yay it works!"; // change
$(c_button).removeClass('vote-down-0').addClass('vote-down-1');
$(c_button).siblings('a.vote-up-0').addClass('vote-up-1').removeClass('vote-up-0'); // ** TODO: this needs to be repeated for all cases below**
break;
case "no_vote":
output = "You've run out of negative votes.";
break;
case "vote_limit":
output = "You can vote anymore today. Limit is 25 per day.";
break;
case "login":
output= "You need to login before you can vote.";
break;
case "own":
output = "You cannot vote on your own comment.";
$(c_button).removeClass('vote-down-0').addClass('vote-down-1');
break;
case "already":
output ="You have already voted on this.";
break;
case "session":
output = "Your login session has expired, please login again.";
break;
}
alert(output);
This reads the response send back via Json and gives a different alert for each case.
Is there an easier way of doing this? How could this be re-factored?
You could try changing the class of your a tags from
<a class="vote-up-0">
to
<a class="vote-0 up">
you could then refactor the two functions as:
$('a.vote-0').click(function() {
var voteType = $(this).is('.up') ? 'up' : 'down';
... snip ...
$.post('user/?action=ajax', {
vote_type: voteType,
reply_id: id,
auth_token: ajax_auth_token
}
...
The code for case success
then simply becomes:
$(c_button).removeClass('vote-0').addClass('vote-1');
$(c_button).siblings('a.vote-0').addClass('vote-1').removeClass('vote-0');
精彩评论