1
我對兩個鏈接使用以下代碼:a.vote-down-0和a.vote-up-0,它們做同樣的事情,除了每一個指定投票是向上還是向下。重構Jquery:解析json
$('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_message)
{
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);
這會讀取通過Json發回的回覆,併爲每種情況提供不同的警報。
有沒有更簡單的方法來做到這一點?這怎麼可以重新考慮?