如果ajax发布失败,如何显示错误消息?

时间:2015-10-23 21:09:49

标签: javascript jquery json ajax

我有一个ajax post请求,如果用户已登录则效果很好但如果用户已注销则会出错。

在控制台中抛出的错误

  

POST http://localhost/r2/public/votes 500(内部服务器错误)

我有一个身份验证门禁止用户投票,如果他们没有登录。到目前为止一切都很好。

但我想在简单的模态窗口中显示自定义的错误消息。

此刻,我正在尝试console.log(),但它没有打印任何东西,我一直得到与上面相同的错误。

$('.topic').upvote();

$('.vote').on('click', function (e) {
    e.preventDefault();
    var $button = $(this);
    var postId = $button.data('post-id');
    var value = $button.data('value');
    $.post('http://localhost/r2/public/votes', {postId:postId, value:value}, function(data) {
    if (data.status == 'failure')
    {
       console.log('You are not logged in.');
    }
   }, 'json');
});

1 个答案:

答案 0 :(得分:2)

请参阅http://api.jquery.com/jquery.post/

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
}).fail(function() {
  alert( "error" );
});

使用500进行身份验证错误并不理想,因为有401个。

相关问题