使用jQuery Ajax過濾實現REST不間斷會話

來源:互聯網
上載者:User

使用jQuery Ajax過濾實現REST不間斷會話
使用jQuery Ajax過濾實現REST不間斷會話

當用戶端與服務端的會話逾時,發出一個Ajax資料請求,遇到403狀態代碼怎麼辦?
在Shell終端裡,超級管理員會話逾時時,會自動顯示密碼輸入確認。對頁面來說,是要捕獲每個狀態代碼為403的失敗請求,待登陸成功後一個個replay,還是在登陸成功後直接重新整理頁面?

jQuery發展到今天,應該會提供處理這種業務的功能。果然找到madpilot rants一篇文章,這些問題都迎刃而解。
具體過程是:
當請求遇到403錯誤後,會被放入403隊列,並彈出登陸框,當登陸成功後,會自動重發隊列中未成功的請求。

不過這個方案目前有一定缺陷:它不支援使用Promise風格添加success回調,success回調得寫在options裡面,也就是說:

//支援jQuery.ajax("/foo.json",{success: function(data){//TODO}});//而不支援jQuery.ajax("/foo.json").done(function(data){//TODO});

以下方案參考了rants的方案,並考慮到了並發請求都403失敗的情形:

require(["jquery"],function($){//Thanks @madpilot rants//See http://myles.eftos.id.au/blog/2011/11/30/how-to-re-play-an-ajax-request-in-jquery-after-an-authentication-error/#.U-iHifmSx8Evar isDialogShown=false;var ajaxQueue=[];jQuery.ajaxSetup({statusCode:{//未登入或登陸後session失效時,服務端會返回狀態代碼403403:function(){ajaxQueue.push(this);if(isDialogShown){return;}isDialogShown=true;require(["infrastructure/user/LoginDialog"],function(LoginDialog){var dialog=new LoginDialog("loginDialog",{onfullfilled:function (){isDialogShown=false;ajaxQueue.forEach(function(context){$.ajax(context);});ajaxQueue.length=0;},onrejected:function(){}});dialog.placeAt(document.body,"beforeEnd")dialog.open();});}}});});


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.